【问题标题】:Tkinter in python3, menubar does not workingpython3中的Tkinter,菜单栏不起作用
【发布时间】:2016-12-07 08:09:31
【问题描述】:

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

上面写着: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()

【问题讨论】:

    标签: python tkinter menubar


    【解决方案1】:

    你正在初始化你的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()
    

    【讨论】:

      【解决方案2】:

      您有一个名为 master=None 的参数,默认为无。因此,当您创建一个不带参数的 ApplicationWindow() 实例时,您的 master 参数将变为无,而在这里您正在调用 config() 方法,但您的 master 没有,并且它没有名为 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
      

      【讨论】:

        猜你喜欢
        • 2015-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-18
        • 2014-12-06
        • 2014-03-10
        • 1970-01-01
        • 2019-05-22
        相关资源
        最近更新 更多