本文介绍了简单的 ttk ComboBox 演示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

在下面的示例中,我需要在每次进行新选择时自动更新 value_of_combo 变量的值.

In the example below, I need the value of value_of_combo variable to be updated automatically every time a new selection is made.

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()

推荐答案

只需将虚拟事件 <<> 绑定到 Combobox 小部件:

Just bind the virtual event <<ComboboxSelected>> to the Combobox widget:

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)
        # ...

这篇关于简单的 ttk ComboBox 演示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 12:32