python - Python AttributeError 实例没有属性
问题描述
我收到以下错误:-
AttributeError: PageOne instance has no attribute 'scann'
我正在尝试运行 bash 脚本(runfocus)。仍然无法弄清楚为什么我会收到此错误。我的代码如下: -
class PageOne(tk.Frame):
def __init__(self, parent, controller):
running = False # Global flag
tk.Frame.__init__(self, parent)
self.controller = controller
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
strt = tk.Button(self, text="Start Scan", command=self.start)
stp = tk.Button(self, text="Stop", command=self.stop)
button.pack()
strt.pack()
stp.pack()
self.after(1000, self.scann) # After 1 second, call scanning
def scann(self):
if running:
sub.call(['./runfocus'], shell=True)
self.after(1000, self.scann)
def start(self):
"""Enable scanning by setting the global flag to True."""
global running
running = True
def stop(self):
"""Stop scanning by setting the global flag to False."""
global running
running = False
请提出您宝贵的建议。
解决方案
AttributeError: PageOne instance has no attribute 'scann' error
由于该running
标志,我无法重现,但您的脚本还有其他问题。你应该避免使用可修改的全局变量,当你已经有了一个类时,绝对没有必要使用一个单独的全局变量。只需创建一个属性作为标志。
这是您的代码的可运行修复版本。我已经sub.call(['./runfocus'], shell=True)
用一个简单的调用替换了调用,print
这样我们就可以看到它start
并stop
正确运行。
import tkinter as tk
class PageOne(tk.Frame):
def __init__(self, parent, controller):
self.running = False
tk.Frame.__init__(self, parent)
self.controller = controller
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
strt = tk.Button(self, text="Start Scan", command=self.start)
stp = tk.Button(self, text="Stop", command=self.stop)
button.pack()
strt.pack()
stp.pack()
self.after(1000, self.scann) # After 1 second, call scanning
def scann(self):
if self.running:
#sub.call(['./runfocus'], shell=True)
print("calling runfocus")
self.after(1000, self.scann)
def start(self):
"""Enable scanning by setting the flag to True."""
self.running = True
def stop(self):
"""Stop scanning by setting the flag to False."""
self.running = False
root = tk.Tk()
frame = PageOne(root, root)
frame.pack()
root.mainloop()
推荐阅读
- javascript - 为什么 VS 代码的变量名有问题?
- php - 数据库从 MySQL 迁移到 SQL Server 后 AJAX 不起作用(未定义索引)
- python - Django 没有从 url 参数中获取 id
- javascript - 将数组中的值添加到另一个数组
- javascript - React formik 部分更新初始值
- css - 如何为除了最后一个元素之外的每个元素制作响应方块,它必须与其他元素具有相同的高度?
- node.js - 如何将存储在 POST 中的变量访问到 GET 函数中?
- python - 如何在 Python 中做柯里化函数
- python - 为什么我的 Python 用户输入代码认为输入不正确
- sharepoint - SharePoint Online 文档库结构:文件夹与文档库与许多网站