Python tkinter 错误 'AboutFrame' object has no attribute 's1' 解决方法
Python tkinter 错误 'AboutFrame' object has no attribute 's1' 解决方法
在使用 Python tkinter 框架时,您可能会遇到如下错误:'AboutFrame' object has no attribute 's1'。这通常是因为您尝试在类方法中访问一个局部函数,而该函数定义在 __init__() 方法内部。
错误原因:
当您在 __init__() 方法内部定义函数 s1() 时,它成为一个局部函数,只在 __init__() 方法内有效。当您在 create_page() 方法中尝试使用 self.s1 调用该函数时,它无法找到该函数,因为 s1 不属于 AboutFrame 类的方法。
解决方案:
将创建函数 s1() 的缩进调整,使其成为 AboutFrame 类的一个方法,而不是 __init__() 方法的一个局部函数。
class AboutFrame(tk.Frame):
def __init__(self, root):
super().__init__(root)
self.root = root
self.create_page()
self.status = tk.StringVar()
def create_page(self):
tk.Label(self, text='关于作品;由tkinter制作').pack()
tk.Label(self, text='关于作者:由智慧警务十一队 彭麟 制作').pack()
tk.Label(self, text='版权所有:智慧警务十一队').pack()
tk.Button(self, text='一共有多少警员', command=self.s1).pack()
tk.Label(self, textvariable=self.status).grid(row=2, column=3, pady=10, stick=tk.E)
def s1(self):
sql = 'SELECT COUNT(id) FROM `警员信息`'
cursor.execute(sql)
res = cursor.fetchone()[0]
self.status.set(f'一共有 {res} 名警员')
修改后的代码:
将函数 s1() 放在类定义内部,并将其设置为 AboutFrame 类的方法。这样,s1() 方法就可以在 AboutFrame 类内部的任何地方被访问。
提示:
- 在定义类方法时,一定要在方法名前添加
self参数。 - 类方法可以通过
self访问类属性和方法。 - 局部函数只能在定义它的方法内访问。
通过以上调整,您就能成功解决 'AboutFrame' object has no attribute 's1' 的错误。
原文地址: https://www.cveoy.top/t/topic/fVih 著作权归作者所有。请勿转载和采集!