pythontkintertkinter-menu

Tkinter menu is not appearing on MacOS 11.2.2


I am trying to create an application to show real-time data in a study on electrical systems. The menu will be used to open information on history of each of the graphs shown on the "front page" and will also include a quit option. When I create the menu and add a couple items to it, it does not show up when I run the application. Unfortunately in my searches, all the alternatives I have tried do not show up either.

from tkinter import *
from tkinter import ttk


class PicoGridInterfacing(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.grid()
        menubar = Menu(root)
        menu = Menu(menubar)
        menubar.add_cascade(label="Menu", menu=menu)
        menu.add_command(label="History", command=None)
        menu.add_command(label="Quit", command=root.quit)

        batteryData = Frame(root)
        batteryData.grid(row=1, column=0)
        Label(batteryData, text="Hello!").grid()


root = Tk()
root.title("Electric Power Systems Lab Pico Grid Interfacing")
app = PicoGridInterfacing(master=root)
root.mainloop()

Here's a screenshot of the output I see: Screenshot of output

Any help would be greatly appreciated, thank you!


Solution

  • Try this:

    from tkinter import *
    from tkinter import ttk
    
    
    class PicoGridInterfacing(Frame):
        def __init__(self, master=None):
            super().__init__(master)
    
            # master = master # `super().__init__(master)` already does that so its useless
    
            # Creating the menu
            menubar = Menu(root)
            menu = Menu(menubar, tearoff=False)
            menubar.add_cascade(label="Menu", menu=menu)
            menu.add_command(label="History", command=None)
            menu.add_command(label="Quit", command=root.destroy)
    
            # Tell the `Tk()` that there is a menu that it need to display:
            master.config(menu=menubar)
    
            batteryData = Frame(self)
            batteryData.grid(row=1, column=0)
            Label(batteryData, text="Hello!").grid()
    
    
    root = Tk()
    root.title("Electric Power Systems Lab Pico Grid Interfacing")
    app = PicoGridInterfacing(master=root)
    # When you inherit from `Frame` you always what the user to call `.grid`
    app.grid()
    root.mainloop()
    

    You need to tell the tkinter.Tk() that there is a menu otherwise it will ignore it. Also when inheriting from tkinter.Frame it's the caller's job to call .grid (it's convention).