简体   繁体   中英

Python tkinter: Add button to menu bar

I am trying to add a button to the far right of the menubar in my program. But it isn't working for me. When I connect it to 'root' it appears below it; when I attach it to 'menubar' or 'filemenu' it doesn't show up at all. Here is my code:

from tkinter import *

root = Tk()

menubar = Menu(root)

# set up button
btn1 = Button(root, text='x')
btn1.pack(side='right', anchor='n', padx=0, pady=0)

filemenu = Menu(menubar,tearoff=0)

# add commands to menu
filemenu.add_command(label="New File")
filemenu.add_command(label="Open")
filemenu.add_command(label="Save")
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)    

root.mainloop()

You cannot do what you want. The menubar is a special, native control that doesn't support the ability to add random buttons to it.

You can use add_command on the menubar itself rather than a submenu, but I think your users would be surprised at this. People generally expect to get a menu when they click on something on the menubar.

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