简单的ttk ComboBox演示

发布于 2021-01-29 17:46:33

这应该很简单,但是我真的很难做到正确。我需要的只是一个简单的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()
关注者
0
被浏览
47
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看