2017-02-25 1 views
-1

변경된 JSON 파일의 텍스트를 기반으로 레이블을 자동으로 업데이트해야합니다. StringVar()은 레이블 텍스트를 변수에 연결하기위한 좋은 내장 tk 솔루션이라는 것을 여러 StackOverflow 게시물에서 읽었습니다.페이지 클래스 python의 tkinter 레이블 텍스트

다른 질문과 다른 점은 아래에 나열된 Page 클래스 (이 페이지의 코드에만 있음)에서 레이블을 업데이트하려고한다는 것입니다. 즉, Page은 큰 응용 프로그램의 어딘가에서 호출되며 Page은 JSON 파일에서 적절한 값으로 레이블을로드해야합니다.

다른 대부분의 게시물은 별도의 메소드 (예 : 페이지의 클릭 이벤트)에서 라벨을 업데이트합니다. 그러나 지속적으로 업데이트되는 json 파일에서 데이터를로드하는 여러 페이지가 있습니다. 나는이 코드를 실행하면

  1. 은 ( 해결) 나는 "PY_VAR1"를 말하는 레이블 텍스트를 얻는다. 이 문제를 어떻게 해결할 수 있습니까?

  2. 처음으로 Page에 액세스 할 때 레이블 텍스트가 정확합니다 (올바르게 초기화되었습니다). 그러나 다른 응용 프로그램 페이지에 액세스 한 후 Page이 반환되면 레이블 텍스트는 업데이트 된 json 값이 아니라 초기화 된 값으로 유지됩니다. 초기화 후 레이블 값을 어떻게 업데이트 할 수 있습니까 Page 코드를 사용하고 있습니까?

주 - Python Tkinter, modify Text from outside the class이 문제와 유사하지만 나는 에서 클래스 내부의 텍스트를 수정하려는.

PY_VAR1 업데이트 : text = "Test Type: {}".format(data['test_type']) 고정

PY_VAR1 문제. 그러나 json 컨텐츠가 변경된 레이블의 성공적인 자동 업데이트를 위해서는 여전히 솔루션이 필요합니다.

import tkinter as tk 
from tkinter import messagebox 
from tkinter import ttk 

# File system access library 
import glob, os 

import json 

class Page(tk.Frame): 
     test_type = tk.StringVar() 

     def __init__(self, parent, controller): 
       tk.Frame.__init__(self, parent) 

       # app controller 
       self.controller = controller 

       test_type = tk.StringVar() 

       # Read json file 
       with open('data.json','r') as f: 
         data = json.load(f) 

       test_type.set(data['test_type']) 

       label = ttk.Label(self, text=str("Test Type: " + str(test_type))) 
       label.pack(pady=1,padx=1, side = "top", anchor = "n") 

       button = ttk.Button(self, text="Previous Page", 
            command=lambda: controller.show_page("Save_Test_Page")) 
       button.pack(pady=1,padx=15, side = "left", expand = "no", anchor = "n") 
+0

당신의'test_type'는 tk.StringVar''의 인스턴스입니다. 'str()'을 사용하면,'tk.StringVar'에 할당 된 이름을 반환 할뿐입니다. – abccd

+0

@abccd'TypeError : encorering 할 때 str()을 사용했기 때문에 'StringVar'객체를 str 암시 적으로 변환 할 수 없습니다. '오류 –

+1

'label = ttk.Label (self, text = "테스트 유형 : {} ". 형식 (데이터 [ 'test_type']))'? – abccd

답변

2
import tkinter as tk 
from tkinter import messagebox 
from tkinter import ttk 

# File system access library 
import glob, os 

import json 

class Page(tk.Frame): 
     test_type = tk.StringVar() 

     def update_lable(self, label): 
       # Read json file 
       with open('data.json','r') as f: 
         data = json.load(f) 
       label['text'] = "Test Type: {}".format(data['test_type']) 
       #rerun this every 1000 ms or 1 second 
       root.after(1000, self.update_lable(label)) #or whatever your root was called 


     def __init__(self, parent, controller): 
       tk.Frame.__init__(self, parent) 

       # app controller 
       self.controller = controller 


       # Read json file 
       with open('data.json','r') as f: 
         data = json.load(f) 


       label = ttk.Label(self, text="Test Type: {}".format(data['test_type'])) 
       label.pack(pady=1,padx=1, side = "top", anchor = "n") 
       self.update_label(label) 
       button = ttk.Button(self, text="Previous Page", 
            command=lambda: controller.show_page("Save_Test_Page")) 
       button.pack(pady=1,padx=15, side = "left", expand = "no", anchor = "n") 
+0

'after'는 꼭 필요한 기능입니다. 감사! 이것은 오랫동안 나를 괴롭혔다 ... –

관련 문제