Home > database >  How to add a menu bar to a Tk() container in python
How to add a menu bar to a Tk() container in python

Time:11-07

I am trying to design a window with a menu bar on top with the controls Add Client,Print Client Lists and Exit. I have imported all required elements from the tkinter library and created a new container for the controls but am getting this error when I try to add the first menu item to the menu bar for k, v in cnf.items():AttributeError: 'str' object has no attribute 'items'

Code

##this is the order.py file responsible for drawing
##the window and ui
from tkinter import *
from Business import *

def add_user():
    print("hello world")
##create a container to hold the components inside the frame
myframe=Tk()
##create the menu bar
menub=Menu(myframe,background='#111', foreground='#111')
##the line below has a bug, i havwe defined the command and the name
menub.add_command('Add Client',command=myframe.quit)
myframe.config(menu=menub)
myframe.mainloop()



CodePudding user response:

You should better read tutorials - you have to use label=...

menub.add_command(label='Add Client', command=myframe.quit)

If you don't use label= then it assigns text to first variable in function's definition - cnf=... - and this variable expects dictionary and it doesn't know what to do with string 'Add Client'. You can even see cnf.items() in error message.


Minimal working example:

import tkinter as tk  # PEP8: `import *` is not preferred

# --- functions ---

def add_user():
    print("hello world")
    
# --- main ---

root = tk.Tk()

menu = tk.Menu(root)
menu.add_command(label='Add Client', command=add_user)
menu.add_command(label='Exit', command=root.destroy)  # `root.quit` may not close window in some situations

root.config(menu=menu)

root.mainloop()

PEP 8 -- Style Guide for Python Code

  • Related