简体   繁体   中英

Drop down button in Tkinter OptionMenu

I need to update my list when I click the button to drop down list:

在此处输入图片说明

How can I bind the button to some function?

The event you're looking for is Activate :

optmenu.bind('<Activate>', onactivate)

Your onactivate callback takes an Activate event, but you probably don't care about its attributes.

The second half of your problem is how to update the menu. To do this, you use the menu attribute, which is a Menu object, on which you can call delete and add and whatever else you want. So, for example:

def onactivate(evt):
    menu = optmenu['menu']
    menu.delete(0, tkinter.END)
    menu.add_command(label='new choice 1')
    menu.add_command(label='new choice 2')
    menu.add_separator()
    menu.add_command(label='new choice 3')
    optvar.set('new choice 1')

(However, notice that, while set ting the var at the end does cause that to become the new default selection, and does show up in the menu header, it doesn't cause the selected item to be highlighted if the cursor isn't over any of the menu items. If you want that, it's tricky, so hopefully you don't.)

'<Activate>' didn't work but i found '<Button-1>' and now it works.

optmenu.bind('<Button-1>', onactivate)

Thank you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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