Tkinter如何根据第一个下拉框自动更新第二个下拉框?

5
我在Tkinter Python中遇到了combobox更新的问题。
我有两个comboboxes:
- combobox A,values=['A','B','C']; - combobox B。
我想要的是:
- 当在combobox A中选择值'A'时,在combobox B中显示值['1','2','3']; - 当在combobox A中选择值'B'时,在combobox B中显示值['11','12','13']; - 当在combobox A中选择值'C'时,在combobox B中显示值['111','112','113']。
目前我的代码部分如下:
def CallHotel(*args):
    global ListB
    if hotel.get()==ListA[0]
        ListB=ListB1
    if hotel.get()==ListA[1]
        ListB=ListB2
    if hotel.get()==ListA[2]
        ListB=ListB3

ListA=['A','B','C']

ListB1=['1','2','3']

ListB2=['11','12','13']

ListB3=['111','112','113']

ListB=ListB1

hotel = StringVar()
hotel.set('SBT')

comboboxA=ttk.Combobox(win0,textvariable=hotel,values=ListA,width=8)
comboboxA.bind("<<ComboboxSelected>>",CallHotel)
comboboxA.pack(side='left')  

stp = StringVar()
stp.set('STP')

comboboxB=ttk.Combobox(win0,textvariable=stp,values=ListB,width=15)
comboboxB.pack(side='left')

1
有什么问题吗?你收到错误信息了吗?请在问题中展示它。 - furas
1个回答

6

实际上,您不需要全局变量ListB。并且您需要在CallHotel()的末尾添加comboboxB.config(values=...)来设置comboboxB的选项:

def CallHotel(*args):
    sel = hotel.get()
    if sel == ListA[0]:
        ListB = ListB1
    elif sel == ListA[1]:
        ListB = ListB2
    elif sel == ListA[2]:
        ListB = ListB3
    comboboxB.config(values=ListB)

直接将comboboxB的初始值更改为ListB1:

comboboxB=ttk.Combobox(win0,textvariable=stp,values=ListB1,width=15)

谢谢您的回答,它没有显示任何错误,只是没有按照我的期望更新列表。 - EMiYiTu
现在,我使用了config函数,所以问题得到解决。 - EMiYiTu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接