python3 中的 Tkinter,菜单栏不工作

Tkinter in python3, menubar does not working

好吧,我想添加菜单栏,但是出了点问题。

它说:AttributeError: 'NoneType' object has no attribute 'config'

我的代码:

from tkinter import *


class ApplicationWindow(Tk):

    def __init__(self, master=None):
        Tk.__init__(self, master)
        self.master = master
        self.geometry('800x400')
        self.f_app = Frame(self).pack()
        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)
        self.b_log = Button(self, width=10, text="Войти", command=self.func).pack()


    def onExit(self):
        self.quit()

    def func(self):
        print("hello")

def main():
    # root = tk
    app = ApplicationWindow() 
    app.mainloop()


if __name__ == '__main__':
    main()

您正在初始化 ApplicationWindow class,但没有传递任何参数,例如 app = ApplicationWindow()。在你的 init 方法中,你给 master 一个 None 默认值,当你尝试使用 master.config 时,它说

'NoneType' object has no attribute 'config'

尝试在初始化 ApplicationWindow 的实例时传入参数。无论您希望 master 成为什么(只是不是 None 对象)。

我已经更新了您的代码(如下)并且它可以运行。按钮起作用,退出函数关闭window。有很多需要修复的地方,但它运行没有错误。从这里开始:

import tkinter


class ApplicationWindow(tkinter.Tk):

    def __init__(self, master=None):
        # Tk.__init__(self, master)
        self.master = master
        self.master.geometry('800x400')
        self.master.f_app = tkinter.Frame(self.master).pack()
        menubar = tkinter.Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = tkinter.Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)
        self.b_log = tkinter.Button(self.master, width=10, text="Войти", command=self.func).pack()


    def onExit(self):
        self.master.destroy()

    def func(self):
        print("hello")

def main():
    root = tkinter.Tk()
    app = ApplicationWindow(root) 
    root.mainloop()


if __name__ == '__main__':
    main()

您有一个名为 master=None 的参数默认为 None。因此,当您创建一个不带参数的 ApplicationWindow() 实例时,您的 master 参数得到 None,在这里您正在调用 config() 方法,但您的 master 是 none 并且它没有名为 config.

的方法
class ApplicationWindow(Tk):
    def __init__(self, master=None):
        ...
        self.master.config(menu=menubar) # Error accurred here

def main():
    # root = tk
    app = ApplicationWindow() # pass an argument