Tkinter 在 python3 中,菜单栏不起作用



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

它说:属性错误:"NoneType"对象没有属性"配置">

我的代码:

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类而不传入任何参数,就像这样app = ApplicationWindow()。 在您的init方法中,您为master提供None默认值,当您尝试使用master.config时,它会显示

">

NoneType"对象没有属性"config">

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

我已经更新了您的代码(如下)并运行。 按钮工作,退出功能关闭窗口。 有很多问题需要修复,但它运行没有错误。 从这里开始:

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()方法,但您的主节点是 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

最新更新