为 ttk 组合框设置默认值
我在 Arch Linux x86_64 中使用 Python 3.2.1。 这真的让我抓狂:我只想在网格化后立即为 ttk.Combobox 提供一个默认的预选值。这是我的代码:
from tkinter import Tk, StringVar, ttk
root = Tk()
def combo(parent):
value = StringVar()
box = ttk.Combobox(parent, textvariable=value, state='readonly')
box['values'] = ('A', 'B', 'C')
box.current(0)
box.grid(column=0, row=0)
combo(root)
root.mainloop()
绘制一个空的Combobox
。有趣的是,如果我不使用函数,它会完美地工作:
from tkinter import Tk, StringVar, ttk
root = Tk()
value = StringVar()
box = ttk.Combobox(root, textvariable=value, state='readonly')
box['values'] = ('A', 'B', 'C')
box.current(0)
box.grid(column=0, row=0)
root.mainloop()
当然,在实际程序中我必须使用函数,所以我需要另一个解决方案。
I'm using Python 3.2.1 in Arch Linux x86_64.
This one is really driving me crazy: I just want to have a default, preselected value for a ttk.Combobox
as soon as I grid it. This is my code:
from tkinter import Tk, StringVar, ttk
root = Tk()
def combo(parent):
value = StringVar()
box = ttk.Combobox(parent, textvariable=value, state='readonly')
box['values'] = ('A', 'B', 'C')
box.current(0)
box.grid(column=0, row=0)
combo(root)
root.mainloop()
Which draws an empty Combobox
. What's funny is that if I don't use a function it works perfectly:
from tkinter import Tk, StringVar, ttk
root = Tk()
value = StringVar()
box = ttk.Combobox(root, textvariable=value, state='readonly')
box['values'] = ('A', 'B', 'C')
box.current(0)
box.grid(column=0, row=0)
root.mainloop()
Of course, in the real program I have to use a function, so I need another solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题在于 StringVar 的实例正在被垃圾收集。这是因为它是一个局部变量,取决于您编写代码的方式。
一种解决方案是使用一个类,以便您的 StringVar 持续存在:
The problem is that the instance of StringVar is getting garbage-collected. This is because it's a local variable due to how you wrote your code.
One solution is to use a class so that your StringVar persists:
当函数“combo”退出时,局部变量“value”将被销毁。您需要一个持久变量,例如全局变量或作为类属性的变量,以便在小部件仍然存在时该值不会被垃圾收集。
When your function 'combo' exits, the local variable 'value' is destroyed. You need a persistent variable, such as a global variable or a variable that is a property of a class so that the value isn't garbage-collected while the widget still exists.
可以在函数中使用
get()
方法来重命名StringVar
并将其保存为其他名称,以避免通过垃圾回收完全丢失它。然后使用keepvalue而不是value:
这在我的组合框中显示了“A”。
The
get()
method can be used within your function to rename theStringVar
and save it under another name to avoid losing it altogether via garbage collection.then use
keepvalue
instead of value:This had 'A' showing in the combobox for me.