问题描述
我在Arch Linux x86_64中使用Python 3.2.1。
这真的让我疯狂:我只想有一个默认值,预先选择的值 ttk.Combobox
一旦我网格。这是我的代码:
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()
绘制一个空 Combobox
。有趣的是,如果我不使用一个函数,它完美地工作:
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.
推荐答案
问题是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.
一个解决方案是使用一个类,使您的StringVar仍然存在:
One solution is to use a class so that your StringVar persists:
from tkinter import Tk, StringVar, ttk
class Application:
def __init__(self, parent):
self.parent = parent
self.combo()
def combo(self):
self.box_value = StringVar()
self.box = ttk.Combobox(self.parent, textvariable=self.box_value,
state='readonly')
self.box['values'] = ('A', 'B', 'C')
self.box.current(0)
self.box.grid(column=0, row=0)
if __name__ == '__main__':
root = Tk()
app = Application(root)
root.mainloop()
这篇关于为ttk组合框设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!