Python Tkinter报错:'_tkinter.tkapp'对象无'tmp'属性求解决
问题分析与修复
报错原因
- 回调函数调用错误:
menuFile.add_command(label='Exit', command=self.ctrl())里的self.ctrl()加了括号,这会在创建菜单时立即执行ctrl方法,而非将其作为点击菜单时触发的回调函数。 - 属性初始化顺序错误:
__init__方法中,你先调用了setup_ui()和self.ctrl(),之后才给self.tmp赋值。当ctrl方法执行时,self.tmp还未被定义,因此触发AttributeError。
修复步骤
- 将
command=self.ctrl()改为command=self.ctrl,去掉括号,让Tkinter把方法本身作为回调,而非立即执行它。 - 调整
__init__里的代码顺序,先初始化self.tmp = True,再调用setup_ui()和self.ctrl(),确保ctrl方法执行时self.tmp已存在。
修改后的完整代码
# -*- coding: utf-8 -*- import tkinter as tk from tkinter.messagebox import * class Application(tk.Tk): def __init__(self): super(self.__class__, self).__init__() self.title('test') self.geometry('300x350') # 先初始化变量 self.tmp = True self.setup_ui() self.ctrl() def ctrl(self): if self.tmp == True: showwarning(title='warning',message='warning') def setup_ui(self): menubar = tk.Menu(self) menuFile = tk.Menu(menubar) menubar.add_cascade(label='File', menu=menuFile) # 去掉括号,传递方法对象作为回调 menuFile.add_command(label='Exit', command=self.ctrl) self.configure(menu=menubar) if __name__ == '__main__': app = Application() app.mainloop()
内容的提问来源于stack exchange,提问作者Danhui Xu
相关产品推荐
相关产品推荐

