[英]Relative OptionMenu list in Tkinter Python
我正在使用GUI将数据插入数据库。我需要创建一个下拉列表(combobox),该列表将根据在另一个下拉列表中选择的值来更改其值。
我尝试使用从第一个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)
您处于正确的位置,但是在mainloop()
之后,此代码不会更改选项,因为它仅在程序开始时运行一次。 您需要在第一个OptionMenu
跟踪StringVar
,并且每当更改它时,就调用一个函数来更改第二个OptionMenu
的选项。 要更改选项,您需要删除现有选项,然后使用add_command()
添加新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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.