Tkinter .set and .get not working in a window inside a window

試著忘記壹切 提交于 2019-12-24 18:13:12

问题


from tkinter import *

def fun():
    trywindow=Tk()
    s=StringVar()
    entry=Entry(trywindow, textvariable=s)
    s.set("print")
    entry.pack()
    trywindow.mainloop()

root=Tk()
fun()

root.mainloop()

According to me after executing this code 2nd window should show enter block with text written in it "PRINTED" but it is blank.


回答1:


As mentioned in the comments, using multiple instances of Tk() is discouraged. It leads to behavior that people don't expect, of which this question is a great example.

As explained in this answer, all instances of Tk are completely isolated. Objects "belonging" to one of them can not be seen or used in the others.
What happens in your code is that you have two Tk instances: root and trywindow. Then you create a StringVar, without any arguments. This is the usual way to do this, but you actually can supply a master widget during construction. This way, you can control to which Tk instance your StringVar "belongs". See this quote from effbot:

The constructor argument is only relevant if you’re running Tkinter with multiple Tk instances (which you shouldn’t do, unless you really know what you’re doing).

If you don't specify the master, a master is chosen implicitly. I do believe it is always the first created instance of Tk. In your case, the StringVar is created with root as its master. Because these Tk instances are completely separated, trywindow and all widgets in it can not "see" the StringVar or any value in it.

So you could fix your code by simply passing trywindow to the SringVar constructuion:

s=StringVar(trywindow)

However, it's probably easier to change trywindow from a Tk instance to a Toplevel widget. This also creates a new window, but it belongs to the same Tk instance so you don't have these difficulties with separate Tk instances:

from tkinter import *

def fun():
    trywindow = Toplevel()
    s = StringVar()
    entry = Entry(trywindow, textvariable=s)
    s.set("print")
    entry.pack()
    trywindow.mainloop()

root = Tk()
fun()

root.mainloop()


来源:https://stackoverflow.com/questions/55208876/tkinter-set-and-get-not-working-in-a-window-inside-a-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!