Calling a Tk instance from another Tk instance causes issue setting textvariables

∥☆過路亽.° 提交于 2019-12-12 06:19:55

问题


I have built a simple user dropdown menu using Tkinter and ttk. I use textvariable.set() to set a default value for the window on loading. Everything works great. Code is below.

from Tkinter import *
import ttk
parent = Tk()

myvalue = StringVar()

user_entry1 = ttk.Combobox(parent, values=['value 1', 'value2'], textvariable=myvalue)
user_entry1.pack()
myvalue.set('default value')
mainloop()

I now want to get a bit more complicated and use another Tk() instance, called root to to generate my parent Tk() instance. Everything seems to work fine, expect the default value for the dropdown doesn't get display. It does get assigned to the textvariable as proven by print myvalue.get(). What am I missing here?

from Tkinter import *
import ttk

root = Tk()

def load_dropdown():
    parent = Tk()
    myvalue = StringVar()

    user_entry1 = ttk.Combobox(parent, values=['value 1', 'value2'], textvariable=myvalue)
    user_entry1.pack()
    myvalue.set('default value')
    print myvalue.get()
    parent.mainloop()

b = Button(root, text="Generate Dropdown ", command=load_dropdown)
b.pack()
root.mainloop()

回答1:


Having two Tk instances confuses it. If you want things displayed in a separate top-level window, call Toplevel() instead and things will work.

def load_dropdown():
    parent = Toplevel()  # <- change to this
    myvalue = StringVar()
    ...



回答2:


You cannot use more than once instance of Tk in a tkinter application. You are observing one of the negative side-effects of trying to do so.

If you need a second window, create an instance of Toplevel rather than a second instance of Tk.




回答3:


In tkinter you only ever create one mainloop which is done by root = Tk()

This is your default window. Your example will work if you get rid of the second creation of parent.

To create more windows use new_window = TopLevel()

There is a lot of good documentation on tkinter, make use of it and it will take you far :)

http://effbot.org/tkinterbook/toplevel.htm

http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/toplevel.html

http://www.tkdocs.com/tutorial/windows.html

https://docs.python.org/2/library/tkinter.html



来源:https://stackoverflow.com/questions/31248376/calling-a-tk-instance-from-another-tk-instance-causes-issue-setting-textvariable

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