简单的ttk ComboBox演示 [英] Simple ttk ComboBox demo

查看:165
本文介绍了简单的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()


推荐答案

只需绑定虚拟事件<< ComboboxSelected>> 到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演示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆