Skip to main content
 首页 » 编程设计

python之tkinter "Class"没有属性 "button"即使在实例中设置

2024年10月17日8daizhj

我正在尝试从这个 tutorial 运行示例并得到一个错误:

self.startBtn.config(state=tk.DISABLED) AttributeError: 'Example' object has no attribute 'startBtn' 

为了简单起见,我重写了我的代码(但仍然出现错误):

  #!/usr/bin/env python3 
 
    import tkinter as tk 
 
 
    class Example(tk.Frame): 
 
        def __init__(self, parent): 
            tk.Frame.__init__(self, parent) 
            self.grid() 
 
            startBtn = tk.Button(self, text="Start", command=self.disableButton) 
            startBtn.grid(row=0, column=0, padx=10, sticky=tk.E) 
 
        def disableButton(self): 
            self.startBtn.config(state=tk.DISABLED) 
 
 
    def main(): 
 
        root = tk.Tk() 
        root.geometry("400x300") 
        app = Example(root) 
        app.mainloop() 
 
 
    if __name__ == '__main__': 
        main() 

我错过了什么?


实现 我忘了提到程序能够编译,但按下按钮时会发生错误。

请您参考如下方法:

在函数中,您使用:

def disableButton(self): 
    self.startBtn.config(state=tk.DISABLED) 

但是 按钮是在没有 self 的情况下创建的:

startBtn = tk.Button(self, text="Start", command=self.disableButton) 
startBtn.grid(row=0, column=0, padx=10, sticky=tk.E) 

简单地做到:

    self.startBtn = tk.Button(self, text="Start", command=self.disableButton) 
    self.startBtn.grid(row=0, column=0, padx=10, sticky=tk.E) 
 
def disableButton(self): 
    self.startBtn.config(state=tk.DISABLED) 

...能够在函数中配置按钮的状态。