I am totally newbie of Python. However i have to use python 3 to do some projects. I am really confused by ttk.Label with textvariable. Below is my codes.
from tkinter import *
from tkinter import ttk
class new_label:
def __init__(self, master):
self.master = master
self.label_var = StringVar()
ttk.Label(self.master, text="iii").grid(row=0, sticky = "w")
self.create_label()
def create_label(self):
self.l1 = ttk.Label(f,
textvariable = self.label_var,
foreground = "red",)
self.l1.grid(row=1)
self.label_var.set("First Label")
print(self.l1.cget("text"))
r=Tk()
r.title("My Label Update")
f=ttk.Frame(r)
f.grid(row=0)
new_label(f)
r.mainloop()
In my codes I add a print and it can print the text well. However the text can't display out and there is no any message of any errors. I do need someone to help for this issue. Thank you very much in advance.
You aren't keeping a reference so the instance of new_label
, so the python garbage collector is collecting it. The ttk widgets are particularly sensitive to the use of garbage-collected StringVar
instances.
The simple solution is to keep a reference to your instance of new_label
:
x = new_label(f)