我正在使用GUI来将数据插入数据库。我需要创建一个下拉列表(组合框),该列表将根据在另一个下拉列表中选择的值来更改其值。
我尝试使用从第一个OptionMenu到基于StringVar的选定值的陈述,但它不起作用。 你有什么建议吗?
Type =('Option1', 'Option2', 'Option3')
CategoryA = ('1','2', '3')
CategoryB= ('A','Transport')
TypeSelected = StringVar()
TypeSelected.set(Type[0])
TypeOption = OptionMenu(self,TypeSelected,*Type)
TypeOption.grid(row=1, column=1)
CategoryLabel = Label(self,text='Category')
CategoryLabel.grid(row=2, column=0)
CategorySelected = StringVar()
print(str(TypeSelected))
if(str(TypeSelected)=='Przychody'):
CategorySelected.set(CategoryPrzychody[0])
category = CategoryPrzychody
else:
CategorySelected.set(CategoryRozchody[0])
category = CategoryRozchody
CategoryOption = OptionMenu(self,CategorySelected,*category)
CategoryOption.grid(row=2,column=1)
答案 0 :(得分:0)
您位于正确的位置,但是此代码不会在调用mainloop()
之后更改选项,因为它仅在程序开始时运行一次。您需要在第一个StringVar
中跟踪OptionMenu
,并且每当它更改时,调用一个函数来更改第二个OptionMenu
中的选项。要更改选项,您需要删除现有选项,然后使用add_command()
添加新选项。例如:
import tkinter as tk
def set_options(*args):
"""
Function to configure options for second drop down
"""
global option, option2, menu2
a = ['1', '2', '3']
b = ['4', '5', '6']
# check something has been selected
if option.get() == '(select)':
return None
# refresh option menu
option2.set('(select)')
menu2['menu'].delete(0, 'end')
# pick new set of options
if option.get() == 'A':
new_options = a
else:
new_options = b
# add new options in
for item in new_options:
menu2['menu'].add_command(label=item, command=tk._setit(option2, item))
root = tk.Tk()
# drop down to determine second drop down
option = tk.StringVar(root)
option.set('(select)')
menu1 = tk.OptionMenu(root, option, 'A', 'B')
menu1.pack()
# trace variable and change second drop down
option.trace('w', set_options)
# second drop down
option2 = tk.StringVar(root)
option2.set('(select)')
menu2 = tk.OptionMenu(root, option2, '(select)')
menu2.pack()
# initialise
set_options()
root.mainloop()