问题
How to make a graded combobox in python Tkinter? Like if we choose a value from first combobox menu, then the next combobox menu will show only values that inside the first selected combobox value category.
This is my code:
BU = StringVar()
BU.set("")
def BU(BU_choices):
s = BU.get()
BU_choices = ["DUM", "IND", "KAM", "RAP"]
BU_drop = OptionMenu(Canv, status, *BU_choices, command=BU)
BU_drop.config(bg="white", fg="dark blue", width=3, relief=GROOVE)
BU_drop.place(x=130, y=110)
sector = StringVar()
sector.set("")
def sector(sector_choices):
s = sector.get()
sector_choices == selected_sector
if BU.get() == "DUM":
selected_sector = ["GRG", "LBO", "KBU", "PLS"]
elif BU.get() == "IND":
selected_sector = ["BYS", "MER", "NGD", "PER"]
sector_drop = OptionMenu(Canv, status, *sector_choices, command=sector)
sector_drop.config(bg="white", fg="dark blue", width=3, relief=GROOVE)
sector_drop.place(x=130, y=150)
Any Suggest?
回答1:
Based on your code with some bugs fixed:
def on_BU_change(BU_selected):
# remove current options in sector combobox
menu = sector_drop['menu']
menu.delete(0, 'end')
# create new options for sector combobox based on selected value of BU combobox
if BU_selected == 'DUM':
selected_sectors = ['GRG', 'LBO', 'KBU', 'PLS']
elif BU_selected == 'IND':
selected_sectors = ['BYS', 'MER', 'NGD', 'PER']
else:
selected_sectors = ['']
# clear the current selection of sector combobox
sector.set('')
# setup the sector combobox
for item in selected_sectors:
menu.add_command(label=item, command=lambda x=item: on_sector_change(x))
BU = StringVar()
BU_choices = ['DUM', 'IND', 'KAM', 'RAP']
BU_drop = OptionMenu(Canv, BU, *BU_choices, command=on_BU_change)
BU_drop.config(bg='white', fg='dark blue', width=3, relief=GROOVE)
BU_drop.place(x=130, y=110)
def on_sector_change(sector_selected):
sector.set(sector_selected)
sector = StringVar()
sector_drop = OptionMenu(Canv, sector, '', command=on_sector_change)
sector_drop.config(bg='white', fg='dark blue', width=3, relief=GROOVE)
sector_drop.place(x=130, y=150)
来源:https://stackoverflow.com/questions/40504864/graded-combobox-menu-python-tkinter