我需要根据更改的JSON文件中的文本自动更新标签。我阅读了几个StackOverflow文章,StringVar()
是一个很好的内置tk解决方案,用于将标签文本链接到变量。更新页面类中的tkinter标签文本python
我的问题与其他帖子的不同之处在于,我试图仅更新下面列出的Page
类(仅在此页面的代码中)更新标签。换句话说,Page
在更大的应用程序中被调用 - Page
需要使用JSON文件中的相应值加载标签。
大多数其他帖子都是通过单独的方法(即页面上的点击事件)来更新标签。但是,我有几个页面从一个不断更新的json文件加载数据。
(解决)当我运行代码,我得到的标签文字说 “PY_VAR1”。我该如何解决?
当第一次访问
Page
时,标签文本是正确的(初始化工作正常)。但是,当访问其他应用程序页面并返回Page
时,标签文本保持初始化值,而不是更新的json值。初始化后如何才能更新标签值只有使用Page
代码?
注 - Python Tkinter, modify Text from outside the class是类似的问题,但我想修改从内类的文字。
PY_VAR1更新:
PY_VAR1问题固定text = "Test Type: {}".format(data['test_type'])
。但是,仍然需要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")
你'test_type'是tk.StringVar'的'一个实例。通过'str()',它只是返回'tk.StringVar'的指定名称。 – abccd
@abccd我使用了str(),因为当我鼓励一个'TypeError:无法将'StringVar'对象隐式转换为str'错误 –
无法执行'label = ttk.Label(self,text =“Test Type :{}“。format(data ['test_type']))'? – abccd