【问题标题】:Tkinter: Combobox disappears when defining a callback functionTkinter:定义回调函数时组合框消失
【发布时间】:2020-10-28 08:04:54
【问题描述】:

我对 Tkinter 很陌生。当我在“颜色 GUI”上创建标签和组合框时,标签和组合框都显示没有问题。我遇到的问题是,当我尝试为该组合框定义回调时,它消失了。

我只是在尝试使用类、实例和方法来练习和理解。任何帮助,将不胜感激。为什么会这样?

 class OOP:
    def __init__(self):
        self.win = tk.Tk()
        self.win.title('Color GUI')
        self.win.geometry('450x400')

# Label for choosing Color
        self.colorlabel = ttk.Label(self.win, text = 'Select a color: ',
            font =("Times New Roman", 10)).grid(column=0,
            row =1,padx=10, pady=10, sticky='W')
# Callback for color combobox
    def color_callback(self, eventObject):
        self.color_choose = eventObject.widget.get()
        if self.color_choose == 'Green':
            print('Hello World')
# Combobox creation for choosing color
        self.n = tk.StringVar
        self.colorList = ['Green', 'Blue', 'Red', 'Orange']
        self.colorchoose = ttk.Combobox(self.win, width=5, textvariable = self.n, value=self.colorList, state='readonly')
        self.colorchoose.grid(column=1, row=1, sticky='W')
        self.colorchoose.bind("<<ComboboxSelected>>", color_callback)

#======================================================================
# Start GUI
#======================================================================
oop = OOP()
oop.win.mainloop()

【问题讨论】:

    标签: class user-interface tkinter combobox callback


    【解决方案1】:

    将您的回调定义移动到组合框创建下方。目前,组合框的创建在回调代码中。

    【讨论】:

    • 我做了,但是,如果我将回调放在组合代码下方,代码无法将回调绑定到组合框
    • @gq1108 您应该在bind(...) 中使用self.color_callback 而不是color_callback。在self.n = tk.StringVar 中也缺少()。
    猜你喜欢
    • 2018-07-03
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多