简体   繁体   中英

Python Function: Tkinter Menu and Menu items

I want to create multiple Menus with their corresponding menu items using a function to avoid repetition of my codes. However, when I try to call the function, it overwrites the previously called function. The sample code is as follows:

from tkinter import Tk, Menu

simple_window = Tk()

def add_menu(simple_window, menu_label, item1="", item2=""):
    # Creating a menu bar
    menu_bar = Menu(simple_window)
    simple_window.config(menu=menu_bar)

    # create menu and add menu items
    file_menu = Menu(menu_bar)              # create menu
    file_menu.add_command(label=item1)      # add menu item
    file_menu.add_command(label=item2)# add menu item
    menu_bar.add_cascade(label=menu_label, menu=file_menu) 


add_menu(simple_window, "File", "New", "Exit")
add_menu(simple_window, "About", "Help")

simple_window.mainloop()

What am I missing here? How will I solve this problem?

You are recreating menu_bar again and again instead create it only once.

Here is your corrected code:

from tkinter import Tk, Menu


def add_menu(menu_label, item1="", item2=""):
    # Creating a menu bar
    

    file_menu = Menu(menu_bar, tearoff=0)              # create menu
    file_menu.add_command(label=item1, command=None)      # add menu item
    file_menu.add_command(label=item2, command=None)# add menu item
    menu_bar.add_cascade(label=menu_label, menu=file_menu) 


simple_window = Tk()

menu_bar = Menu(simple_window)
simple_window.config(menu = menu_bar)

add_menu( "File", "New", "Exit")
add_menu("About", "Help")
add_menu("edit", "Settings", "Exit")

simple_window.mainloop()

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