Skip to content Skip to sidebar Skip to footer

Tkinter .set And .get Not Working In A Window Inside A Window

from tkinter import * def fun(): trywindow=Tk() s=StringVar() entry=Entry(trywindow, textvariable=s) s.set('print') entry.pack() trywindow.mainloop() root

Solution 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()

Post a Comment for "Tkinter .set And .get Not Working In A Window Inside A Window"