0

I have written the below code to create a tkinter form with a menu bar, I am using the canvas widget to arrange all the buttons and labels, however I am not able to show the menubar on the canvas below is the code I have written to do this:

from tkinter import *
import tkinter as tk

window = Tk() 
window.title("test")
window.geometry("500*500")
canvas1 = Canvas(window, width= 500, height= 500, bg = 'midnight blue')
menubar = tk.Menu(window)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New",command=dosomething)
filemenu.add_command(label="Edit",command=dosomething)
button1 = tk.Button(window, text="Say Hello")

window.config(menu = menubar)
canvas1.create_window(100,100, window = button1)
window.mainloop()

I am not sure how to display the menubar on the top of the canvas, please help on how to do this.

1 Answers1

2

There are several issues in your code:

  1. You are not displaying your canvas, don't forget to pack or grid it in the window.

  2. You create a sub-menu called filemenu but you don't add it in your menubar. Therefore menubar is empty, that's why you don't see it, even though window.config(menu=menubar) is the right way to display it in your window. Here is the missing line:

     menubar.add_cascade(label='File', menu=filemenu)
    
  3. There is a typo in the window geometry: window.geometry("500*500") should be window.geometry("500x500").

  4. The lines

     from tkinter import *
     import tkinter as tk
    

    are redundant, you are importing tkinter twice. I advise you to remove from tkinter import * (see explanations here: Why is "import *" bad?, What exactly does "import *" import?)

Here is the full code:

import tkinter as tk

def dosomething():
    print('do something')
    
window = tk.Tk() 
window.title("test")
window.geometry("500x500")
canvas1 = tk.Canvas(window, width=500, height=500, bg='midnight blue')
menubar = tk.Menu(window)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=dosomething)
filemenu.add_command(label="Edit", command=dosomething)
menubar.add_cascade(label='File', menu=filemenu)
button1 = tk.Button(window, text="Say Hello")

window.config(menu=menubar)
canvas1.create_window(100, 100, window=button1)
canvas1.pack()
window.mainloop()
j_4321
  • 15,431
  • 3
  • 34
  • 61