[英]My inherited class MenuBar(tk.Menu) does not showing Menubar
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.我并不完全理解 python3 的类结构,因为我对它编程还很陌生。 I am running on ubuntu 18.04 and here is the code I am having trouble with.我在 ubuntu 18.04 上运行,这是我遇到问题的代码。
#! /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问题:tkinter ...没有显示主菜单
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
.在这里,您创建一个新的tk.Menu(...
with parent ==self
。
The Variablemenubar
hold thetk.Menu(...
object.变量menubar
包含tk.Menu(...
对象。menubar = tk.Menu(self, tearoff=False)
A
class __init__
methode returns itself, therefore you don't return the newmenubar
.class __init__
方法返回自身,因此您不会返回新的menubar
。
You return aclass MenuBar(tk.Menu)
object, which ist empty !你返回一个class MenuBar(tk.Menu)
对象,它是空的!
change to改成
class MenuBar(tk.Menu):
def __init__(self, parent):
Your class MenuBar
is the new menubar!你的class MenuBar
是新的菜单栏! Therefore, the init parameters goes here因此, init参数放在这里
tk.Menu.__init__(self, parent, tearoff=False)
The submenus parent
is this class, therefore pass self
.子菜单parent
类是此类,因此传递self
。
filemenu = tk.Menu(self, tearoff=0)
Add filemenu
items as used根据使用情况添加文件filemenu
项
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...
。
self.add_cascade(label="File", menu=filemenu)
You can .config(...
within class MenuBar
doing:您可以.config(...
在class MenuBar
执行以下操作:
parent.config(menu=self)
Tested with Python: 3.5 - TkVersion': 8.6用 Python 测试:3.5 - TkVersion':8.6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.