【问题标题】:Simple ttk ComboBox demo简单的 ttk ComboBox 演示
【发布时间】:2025-11-30 18:50:01
【问题描述】:

这应该很简单,但我真的很难做到正确。 我只需要一个简单的 ttk ComboBox,它会在选择更改时更新变量。

在下面的示例中,我需要在每次进行新选择时自动更新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()

【问题讨论】:

    标签: python tkinter combobox ttk


    【解决方案1】:

    只需将虚拟事件<<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)
            # ...
    

    【讨论】:

      【解决方案2】:

      在更一般的情况下,如果您需要在更新时获取变量的值,建议使用内置的跟踪工具。

      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
      

      【讨论】: