Search code examples
pythontkinter

Tkinter menu spontaneously adding extra item


I'm writing a Tkinter program that so far creates a window with a menu bar, a File menu, and a single item. The menu is successfully created, but with two items, the first being one that I did not specify, whose name is "-----".

If I don't add an item, the spontaneous one is still added. This still happens if I specify tearoff=0.

Any idea why this is happening?

Windows 11, Python 3.12.2, Tkinter and Tcl 8.6.

import tkinter as tk

window = tk.Tk()
window.geometry("800x600")

menubar = tk.Menu(window)
window.config(menu=menubar)

fileMenu = tk.Menu(menubar)
fileMenu.add_command(
    label="Exit",
    command=window.destroy,
)
menubar.add_cascade(label="File", menu=fileMenu, underline=0)

window.mainloop()

Solution

  • In that way it works. I think u put tearoff=0 in menubar instead of fileMenu. If you put your tearoff=0 in menubar it won't affect fileMenu. So, u need to specifically put tearoff=0 in specific tk.Menu()

    import tkinter as tk
    
    window = tk.Tk()
    window.geometry("800x600")
    
    menubar = tk.Menu(window)
    window.config(menu=menubar)
    
    fileMenu = tk.Menu(menubar,tearoff=0)
    fileMenu.add_command(
        label="Exit",
        command=window.destroy,
    )
    menubar.add_cascade(label="File", menu=fileMenu, underline=0)
    
    window.mainloop()