【问题标题】:Adding a menu bar in constructor function在构造函数中添加菜单栏
【发布时间】:2022-01-27 08:41:55
【问题描述】:

除了一些功能性按钮之外,我正在尝试添加菜单栏,但每次尝试添加菜单栏代码时仍然会出现一些错误,应该添加什么代码才能让我在这里有菜单栏?

抱歉添加了一大堆代码

from tkinter import *
from PIL import Image, ImageTk
import cv2

class GUI(tk.Frame):
    img = None
    img_is_found = False

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)

        self.grid(sticky=N + S + E + W)

        # Browse button
        self.file = Button(self, text='Browse', command=self.choose,
                           bg="#20bebe", fg="white", height=2, width=15)   

        #displayed image in label
        self.label = Label(image=None, width=900, height=600)


        ***#Menubar- this is the piece of code that causes the error**
        menubar = MenuBar(self)
        self.config(menu=menubar)
        fileMenu = tk.Menu(self, tearoff=False)
        self.add_cascade(label="File", underline=0, menu=fileMenu)
        fileMenu.add_command(label="Copy", underline=1, command=app.copy_stuff)


        self.pack()
        self.label.pack()
        self.file.pack()

    def choose(self):
       pass



root = Tk()
root.title('image ToolBox')

gui = GUI(root)
gui.mainloop() 

#错误日志

  File "/home/mma/PycharmProjects/img-proj/test.py", line 43, in __init__
    menubar = MenuBar(self)
NameError: name 'MenuBar' is not defined. Did you mean: 'menubar'?

###################

如果我删除了菜单栏代码块,实际上没有发生错误:)

the ui when running the code without the menubar piece of code

【问题讨论】:

  • 你认为MenuBar 来自哪里?看起来您不是从任何地方导入的。
  • @BryanOakley,您能建议正确的导入方式吗?
  • 不,我不能,因为我不知道它是什么。 Tkinter 没有 MenuBar 小部件,所以我不知道您要使用什么小部件。
  • 在这里提问时,您应该提供一个minimal reproducible example,其中包含足够 代码来说明问题 - 并非您程序中的所有代码都包含各种里面有不相关的东西。
  • @martineau ,好的,问题编辑了足够的代码,打扰了,但这是第一次在这里提问,

标签: python user-interface tkinter


【解决方案1】:

我猜你在任何地方都没有真正的 MenuBar 类,而是错误地认为它来自 tkinter。 Tkinter 没有 MenuBar 小部件,但它有一个 Menu 小部件,您可以从中创建菜单栏。

您犯的下一个错误是试图将菜单附加到框架上。框架没有menu 选项,只有根窗口和Toplevel 小部件有。

另一个错误是尝试在self 上调用add_cascade。这是菜单上的方法,而不是自定义类上的方法。

最后,除非有非常令人信服的理由(而且很少这样做),否则菜单应该是它们被添加到的菜单的子菜单。

您需要将代码更改为如下所示:

menubar = Menu(master)
master.config(menu=menubar)

fileMenu = Menu(menubar, tearoff=False)
menubar.add_cascade(label="File", underline=0, menu=fileMenu)
fileMenu.add_command(label="Copy", underline=1, command=app.copy_stuff)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多