python - 我继承的类 MenuBar(tk.Menu) 不显示菜单栏

标签 python python-3.x inheritance tkinter menu

我一直在尝试向我的程序添加主菜单,但遇到了问题。 我不太了解 python3 的类结构,因为我对使用它进行编程相当陌生。 我正在 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()

我没有出现文件菜单。有什么帮助吗?

最佳答案

Question: tkinter ... not showing Main Menu

这里有几个问题。

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 Variable menubar hold the tk.Menu(... object.

    menubar = tk.Menu(self, tearoff=False)

一个class __init__ methode 返回自身,因此您返回新的 menubar .
您返回 class MenuBar(tk.Menu)对象,它是!

更改为

class MenuBar(tk.Menu):
    def __init__(self, parent):
  • 您的class MenuBar 新的菜单栏!因此,init参数放在这里

        tk.Menu.__init__(self, parent, tearoff=False)
    
  • 子菜单parent是这个类,因此通过 self .

        filemenu = tk.Menu(self, tearoff=0)
    
  • 添加filemenu使用过的元素

        filemenu.add_command(label="Test", command=self.test_Test)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=lambda: self.controller.quitButton())
    
  • 将子菜单添加到该对象,因此使用 self.add... .

        self.add_cascade(label="File", menu=filemenu)
    
<小时/>

您可以.config(... class MenuBar内做:

        parent.config(menu=self)

使用 Python 测试:3.5 - TkVersion':8.6

关于python - 我继承的类 MenuBar(tk.Menu) 不显示菜单栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147637/

相关文章:

python - 未找到数据源名称且无默认驱动程序错误

python - 根据文件类型为文件名添加 LasWriteTime 前缀

python - 尝试使用 Colorama 时出现 AttributeError(我知道这不是一个好标题)

c# - 奇怪的继承修改

python - 将 "True"转换为真正的 JSON Python

python - 将 Qt 嵌入 native 窗口 (Windows)

python 3 : How to use print() to print a string with quote?

html - 如何将 django forms.py 选择项转换为 html 列表?

c++ - 从基类使用和重新定义 typedef

c# - 继承 ICollection<T> 的抽象基类