I have been trying to add a main menu to my program and am having trouble with it. I don't exactly understand the class structure of python3 as I'm fairly new to programming with it. I am running on ubuntu 18.04 and here is the code I am having trouble with.
#! /usr/bin/env python3
import tkinter as tk
from tkinter import *
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
menubar = MenuBar(self)
self.config(menu=menubar)
def quitButton(self):
self.destroy()
class MenuBar(tk.Menu):
def __init__(self, parent):
tk.Menu.__init__(self, parent)
self.controller = parent
menubar = tk.Menu(self, tearoff=False)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Test", command=self.test_Test)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=lambda: self.controller.quitButton())
menubar.add_cascade(label="File", menu=filemenu)
def test_Test(self):
print("This is a test")
if __name__ == "__main__":
app = Application()
app.title("test")
app.mainloop()
The file menu does not appear for me. Any Help?
Question : tkinter ... not showing Main Menu
There are couple problems here.
class MenuBar(tk.Menu): def __init__(self, parent): tk.Menu.__init__(self, parent) self.controller = parent
Here, you create a new
tk.Menu(...
with parent ==self
.
The Variablemenubar
hold thetk.Menu(...
object.menubar = tk.Menu(self, tearoff=False)
A
class __init__
methode returns itself, therefore you don't return the newmenubar
.
You return aclass MenuBar(tk.Menu)
object, which ist empty !
change to
class MenuBar(tk.Menu):
def __init__(self, parent):
Your class MenuBar
is the new menubar! Therefore, the init parameters goes here
tk.Menu.__init__(self, parent, tearoff=False)
The submenus parent
is this class, therefore pass self
.
filemenu = tk.Menu(self, tearoff=0)
Add filemenu
items as used
filemenu.add_command(label="Test", command=self.test_Test) filemenu.add_separator() filemenu.add_command(label="Exit", command=lambda: self.controller.quitButton())
Add the submenu to this object, therefore use self.add...
.
self.add_cascade(label="File", menu=filemenu)
You can .config(...
within class MenuBar
doing:
parent.config(menu=self)
Tested with Python: 3.5 - TkVersion': 8.6
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.