tkinter: creating/attaching menubar to top level window

Rich Shepard rshepard at appl-ecosys.com
Fri Jan 8 16:47:35 EST 2021


I'm using Chapter 9 in Mark Roseman's "Modern Tkinter for Busy Python
Developers" to learn how to write a top level menu. MWE code is attached.

Python3 tells me there's invalid syntax on line 42:
     self.['menu'] = menubar # attach it to the top level window
          ^
yet that's the syntax he prints on page 84 (and has in the book's code
supplement).

Why am I getting an invalid syntax error here?

TIA,

Rich
-------------- next part --------------
#!/usr/bin/env python3

# main file to start application.
from os import environ
import sys
import pdb
from datetime import datetime
import tkinter as tk
from tkinter import ttk
from tkinter import Menu
from tkinter import filedialog
from tkinter import messagebox
from tkinter.font import nametofont
from functools import partial
import model as m
import views as v
import controller as c


class Application(tk.Tk):
    """ Application root window """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # the top level frame holding menu, status bar, etc.
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.geometry('800x600')
        self.title("Frame title")
        self.resizable(width=True, height=True)

        datestring = datetime.today().strftime("%Y-%m-%d")
        
        # status bar
        self.status = tk.StringVar()
        self.statusbar = ttk.Label(self, textvariable=self.status)
        self.statusbar.grid(sticky="we", row=3, padx=10)

        # toplevel window menu
        menubar = Menu(self) # create a Menu widget
        self.['menu'] = menubar # attach it to the top level window
        """ Add menus to menubar """
        self.menu_file = Menu(menubar, tearoff=0)
        self.menu_view = Menu(menubar, tearoff=0)
        self.menu_add = Menu(menubar, tearoff=0)
        self.menu_edit = Menu(menubar, tearoff=0)
        self.menu_report = Menu(menubar, tearoff=0)
        self.menu_help = Menu(menubar, tearoff=0)
        """ Add menu items to menus """
        menubar.add_cascade(menu_file, label='File')
        menubar.add_cascade(menu_view, label='View')
        menubar.add_cascade(menu_add, label='Add')
        menubar.add_cascade(menu_edit, label='Edit')
        menubar.add_cascade(menu_report, label='Report')
        menubar.add_cascade(menu_help, label='Help')

if __name__ == "__main__":
    app = Application()
    app.mainloop()


More information about the Python-list mailing list