繁体   English   中英

获取 Combobox 的值,同时它们被绑定

[英]Get Value of Combobox, while they are bound

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

我的问题是,我想知道选择了哪种颜色。

因为如果我打印(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的选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM