在绑定时获取 Combobox 的值

Get Value of Combobox, while they are bound

我在 Tkinter 中创建了两个组合框。在第一个框中 select Material,第二个框对第一个框的 selected 值做出反应并更改可用选项。这可能不是最好的编码方式,但它确实有效。

我的问题是,我想知道 selected 是哪种颜色。

因为如果我打印 (Box_2.get()) 它将是空的。

win = Tk()
win.title("Window")

Material_List = ["Material1","Material2"]
Colour_List = ["Green","Blue","Black","White"]

def Print_Colour():     #should print the selected colour 
    print(Box_2.get())

def Select_Mat(eventObject):  #bound to the Material selection and will change the color options. 
    Material_Choice = Box_1.get()
    if Material_Choice == Material_List[0]:
        Box_2 = Combobox (win, values=[Colour_List[0],Colour_List[1]], width=17, state='readonly')
        Box_2.grid(row=1, column=4, columnspan=2)
    elif Material_Choice == Material_List[1]:
        Box_2 = Combobox (win, values=[Colour_List[2],Colour_List[3]], width=17, state='readonly')
        Box_2.grid(row=1, column=4, columnspan=2)

Box_1 = Combobox (win, values=[Material_List[0],Material_List[1]], width=17, state='readonly')
Box_1.grid(row=1, column=1, columnspan=2)

Box_2 = Combobox (win, width=17, state='readonly')
Box_2.grid(row=1, column=4, columnspan=2)

Box_1.bind("<<ComboboxSelected>>", Select_Mat)

Print_Button = Button (win, text="Print Colour", width=16, command=Print_Colour) 
Print_Button.grid(row=2, column=1, columnspan=2)


win.mainloop()

试试这个:

from tkinter import *
from tkinter.ttk import Combobox


win = Tk()
win.title("Window")

Material_List = ["Material1","Material2"]
Colour_List = ["Green","Blue","Black","White"]

def Print_Colour():     #should print the selected colour 
    print(Box_2.get())

def Select_Mat(eventObject):  #bound to the Material selection and will change the color options. 
    Material_Choice = Box_1.get()
    if Material_Choice == Material_List[0]:
        Box_2.config(values=[Colour_List[0], Colour_List[1]])
    elif Material_Choice == Material_List[1]:
        Box_2.config(values=[Colour_List[2], Colour_List[3]])
    Box_2.set("") # Clear Box_2's selection

Box_1 = Combobox(win, values=[Material_List[0], Material_List[1]], width=17, state='readonly')
Box_1.grid(row=1, column=1, columnspan=2)

Box_2 = Combobox(win, width=17, state='readonly')
Box_2.grid(row=1, column=4, columnspan=2)

Box_1.bind("<<ComboboxSelected>>", Select_Mat)

Print_Button = Button(win, text="Print Colour", width=16, command=Print_Colour) 
Print_Button.grid(row=2, column=1, columnspan=2)


win.mainloop()

您的代码存在的问题是您不断创建新的 Box_2 小部件。相反,您应该只使用 .config 方法来更改它们的 values。此外,每次用户选择与 Box_1 不同的内容时,它都会清除 Box_2 的选择。