从另一个 Tk 实例调用一个 Tk 实例会导致设置 textvariables 的问题 [英] Calling a Tk instance from another Tk instance causes issue setting textvariables

查看:60
本文介绍了从另一个 Tk 实例调用一个 Tk 实例会导致设置 textvariables 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Tkinterttk 构建了一个简单的用户下拉菜单.我使用 textvariable.set() 为加载的窗口设置默认值.一切都很好.代码如下.

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

我现在想要更复杂一点,并使用另一个 Tk() 实例,称为 root 来生成我的 parent Tk() 实例.一切似乎都正常,期望下拉列表的默认值不会显示.正如 print myvalue.get() 所证明的那样,它确实被分配给了文本变量.我在这里错过了什么?

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

推荐答案

有两个 Tk 实例会混淆它.如果您希望在单独的顶级窗口中显示内容,请调用 Toplevel() 相反,事情会奏效.

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

这篇关于从另一个 Tk 实例调用一个 Tk 实例会导致设置 textvariables 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆