Python AttributeError实例没有属性

时间:2018-05-25 10:44:50

标签: python tkinter 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

请提供宝贵的建议。

1 个答案:

答案 0 :(得分:0)

我无法重现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()