Python 简单的 ttk ComboBox 演示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17757451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple ttk ComboBox demo
提问by bhaskarc
This should be very simple but I am really struggling to get it right. All I need is a simple ttk ComboBox which updates a variable on change of selection.
这应该很简单,但我真的很难做到正确。我只需要一个简单的 ttk ComboBox,它会在选择更改时更新变量。
In the example below, I need the value of value_of_combo
variable to be updated automatically every time a new selection is made.
在下面的示例中,我需要在value_of_combo
每次进行新选择时自动更新变量的值。
from Tkinter import *
import ttk
class App:
value_of_combo = 'X'
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)
self.box['values'] = ('X', 'Y', 'Z')
self.box.current(0)
self.box.grid(column=0, row=0)
if __name__ == '__main__':
root = Tk()
app = App(root)
root.mainloop()
采纳答案by A. Rodas
Just bind the virtual event <<ComboboxSelected>>
to the Combobox widget:
只需将虚拟事件绑定<<ComboboxSelected>>
到 Combobox 小部件:
class App:
def __init__(self, parent):
self.parent = parent
self.value_of_combo = 'X'
self.combo()
def newselection(self, event):
self.value_of_combo = self.box.get()
print(self.value_of_combo)
def combo(self):
self.box_value = StringVar()
self.box = ttk.Combobox(self.parent, textvariable=self.box_value)
self.box.bind("<<ComboboxSelected>>", self.newselection)
# ...
回答by Tritium21
In the more general case, if you need to get the value of a Variable when it is updated, it would be advisable to use the tracing facility built into them.
在更一般的情况下,如果您需要在更新时获取变量的值,建议使用内置于其中的跟踪工具。
var = StringVar() # create a var object
# define the callback
def tracer(name, idontknow, mode):
# I cannot find the arguments sent to the callback documented
# anywhere, or how to really use them. I simply ignore
# the arguments, and use the invocation of the callback
# as the only api to tracing
print var.get()
var.trace('w', tracer)
# 'w' in this case, is the 'mode', one of 'r'
# for reading and 'w' for writing
var.set('Foo') # manually update the var...
# 'Foo' is printed