Tkinter在Python 3中,菜单栏不工作
嗯,我想添加菜单栏,但出现了一些问题 它说:AttributeError:'NoneType'对象没有属性'config' 我的代码:Tkinter在Python 3中,菜单栏不工作,python,tkinter,menubar,Python,Tkinter,Menubar,嗯,我想添加菜单栏,但出现了一些问题 它说:AttributeError:'NoneType'对象没有属性'config' 我的代码: from tkinter import * class ApplicationWindow(Tk): def __init__(self, master=None): Tk.__init__(self, master) self.master = master self.geometry('800x4
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()
方法,但是您的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