Search code examples
pythontkintermenu

Change tkinter menu when a USB device is plugged in or taken out


I have a tkinter menu / menubar (NOT an OptionsMenu!) with main 'header' category called 'Donations'. I want it so that when this main category has a mouse 'Enter' event happen over it, or, when the header is actually mouse-clicked upon, then a function will run. Part of the function should clear out any *old 'items' in this 'Donations' category, and proceed to give a refreshed set of menu items in the 'Donations' category from which a user can then happily select one of the newly refreshed items.

Setting the initial items within Donations and repopulating them later is not the problem, but the or clicking on the main category to make the function run and CLEARING out the old items is my problem.

import tkinter as tk

root = tk.Tk()
root.geometry("300x220")

def foo():
    pass

def clear_and_repopulate():
    pass

menubar = tk.Menu(root)

# donations
donations_list = ["$1", "$2", "$3"]
donation_menu_item = tk.Menu(menubar, tearoff=0)
# When mouse 'Enter'  OR
# donation_menu_item  header category clicked,
# then run function "clear_and_repopulate"

menubar.add_cascade(label="Donations", menu=donation_menu_item) # Shows the caption
for donation in donations_list: donation_menu_item.add_command(label=donation, command = foo())

root.config(menu=menubar)
root.mainloop()

Appreciative of any guidance/help here. Tq.


Solution

  • When creating a menu, you can specify a postcommand, which is a command that will be called immediately before the menu is posted. Within that function you can delete all of the items and add new items.

    Here's a contrived example that updates the menu with a random number of items each time you click on it:

    import tkinter as tk
    import random
    
    root = tk.Tk()
    
    menubar = tk.Menu(root)
    root.configure(menu=menubar)
    
    def update_donations_menu():
        donations_menu.delete(0, "end")
    
        for i in range(random.randint(1, 6)):
            donations_menu.add_command(label=f"${i}.00")
    
    donations_menu = tk.Menu(menubar, postcommand=update_donations_menu)
    menubar.add_cascade(label="Donations", menu=donations_menu)
    
    tk.mainloop()
    

    screenshot #1

    screenshot #2