首页 > 解决方案 > 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

请提出您宝贵的建议。

标签: pythontkinterattributeerror

解决方案


AttributeError: PageOne instance has no attribute 'scann' error由于该running标志,我无法重现,但您的脚本还有其他问题。你应该避免使用可修改的全局变量,当你已经有了一个类时,绝对没有必要使用一个单独的全局变量。只需创建一个属性作为标志。

这是您的代码的可运行修复版本。我已经sub.call(['./runfocus'], shell=True)用一个简单的调用替换了调用,print这样我们就可以看到它startstop正确运行。

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()

推荐阅读