I need to automatically update a label based on text in a changing JSON file. I read in several StackOverflow posts that StringVar()
is a good built-in tk solution for linking label text to a variable.
My question differs from other posts in that I am attempting to update the label only from the Page
class listed below (in just the code for this page). In other words, Page
is called somewhere in a larger app - and Page
needs to load the label with the appropriate value from the JSON file.
Most other posts approach label updating from a separate method (i.e. a click event on the page). However, I have several pages that load data from a json file that is constantly updating.
(resolved) When I run the code I get label text saying "PY_VAR1". How do I fix this?
When
Page
is first accessed, the label text is correct (initialize did its work correctly). However, when other app pages are accessed and thenPage
is returned to, the label text stays at the initialized value, not the updated json value. How can the label value be updated after initialization only usingPage
code?
Note - Python Tkinter, modify Text from outside the class is similar to the issue, but I want to modify the text from inside the class.
PY_VAR1 Update:
PY_VAR1 issue fixed with text = "Test Type: {}".format(data['test_type'])
. However, still need solution for successful auto-updates of the label with json content changes.
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")