The following Python 3 code has a label and an Entry field that are correctly initialized with a string ("junk" in the example). But when the second "import" line is uncommented to replace the old Entry widget with the new themed widget, the label and Entry fields are not initialized.
Any clue why the themed widget initialization is b开发者_运维技巧roken?
from tkinter import *
# from tkinter.ttk import *
class myApp:
def __init__(self, root):
v = StringVar()
v.set("junk")
label = Label(root, textvariable=v)
label.pack()
text_entry = Entry(root, textvariable=v)
text_entry.pack()
root = Tk()
root.title("MyApp")
app = myApp(root)
root.mainloop()
The problem is that v
is a local variable. When it goes out of scope (ie: when __init__
finishes executing), v
is getting garbage-collected. Change v
to self.v
and the problem goes away.
Why you see the problem with the ttk Entry widget and not the standard one, I don't know. I guess one is just more sensitive to the garbage collector, or perhaps importing both libraries somehow triggers the garbage collector sooner. Regardless, even with the stock widgets you would eventually have some sort of problem because v
will always eventually get garbage-collected.
精彩评论