当使用事件在线程中循环时,如何修复窗口对象没有属性\u stop\u thread?

2024-10-08 18:22:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,在用户不在时自动执行某个任务。程序有一个带有Tkinter的GUI,用户可以随时启动和停止执行。为了控制重复性任务的执行,我使用了一个循环,它在没有设置线程事件时执行。下面所示的窗口类的构造函数初始化了名为stop_thread的变量中的线程事件,但是当我在线程函数内的while循环中使用它来确定是否执行任务时,我得到了一个AttributeError,表示窗口类没有stop\u线程

我当前的Python版本是3.7.4,我已经在IDLE和PyCharm中测试了这个程序,但都给出了相同的错误

我在下面上传了我的部分代码

from tkinter import *
import random
import time
from threading import Thread,Event

class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()                  
        self.backgroundThread=Thread(name='bgTask',
                              target=self.s_i())
        self.stop_thread = Event()

    def init_window(self):
        self.master.title = "Test"
        self.grid()
        text = Label(self, text="Test")
        text.config(font=('Arial', 20, 'bold'))
        text.grid(row=0, column=0, columnspan=3, sticky="nsew")

        start=Button(self,text="Start",command=lambda:self.start())
        start.grid(row=1,column=0,sticky="nsew")

        stop = Button(self, text="Stop", command=lambda: self.stop())
        stop.grid(row=1, column=2,sticky="nsew")

        for i in range(3):
            self.columnconfigure(i,weight=1)

    def s_i(self):
        print('Test has started')
        while not self.stop_thread.isSet():
            time.sleep(15)
            #do something
            print("Hi")
            time.sleep(0.1)
            #do something
            print("Hi")
            time.sleep(0.1)
            #do something
            print("Hi")
            time.sleep(0.1)
            #do something
            print("Hi")
            delay = round(random.uniform(1, 10), 2)
            sleep_time = delay * 60
            time.sleep(sleep_time)

    def start(self):
        self.backgroundThread.start()

    def stop(self):
        self.stop_thread.set()







root = Tk()
root.columnconfigure(0,weight=1)
app = Window(root)
root.mainloop()

我希望代码运行,当我在窗口中点击start时,任务将重复运行,直到我点击stop。相反,我得到以下错误:

Traceback (most recent call last):
  File "/Users/Steven/Desktop/Projects/Python/SITG/SITG.py", line   63, in <module>
app = Window(root)
  File "/Users/Steven/Desktop/Projects/Python/SITG/SITG.py", line 12, in __init__
self.backgroundThread = Thread(name='bgTask',target=self.s_i())
  File "/Users/Steven/Desktop/Projects/Python/SITG/SITG.py", line 32, in s_i
while not self.stop_thread.isSet():
AttributeError: 'Window' object has no attribute 'stop_thread'

Tags: textimportselfmastertimeinitdefsleep
1条回答
网友
1楼 · 发布于 2024-10-08 18:22:21

您的问题在__init__()函数中:

    self.backgroundThread=Thread(name='bgTask',
                          target=self.s_i())

您希望target=self.si,将self.si标识为一个函数,稍后调用

但是你有target=self.si(),这意味着这个函数实际上被调用了,现在还没有定义self.stop_thread

相关问题 更多 >

    热门问题