【发布时间】:2020-08-09 16:50:24
【问题描述】:
我一直在尝试使用此答案提供的代码:
Terminate the Thread by using button in Tkinter
但是每次我运行它时,当我单击按钮时都会收到以下错误消息:
self.stop_threads.clear() AttributeError:“事件”对象没有属性“清除”
self.stop_threads.set() AttributeError:“事件”对象没有属性“设置”
我知道这一定很简单,但我真的很难过任何建议/指针都将不胜感激。
from threading import Thread,Event
from subprocess import call
from tkinter import *
import tkinter as tk
class Controller(object):
def __init__(self):
self.thread1 = None
self.thread2 = None
self.stop_threads = Event()
def loop1(self):
while not self.stop_threads.is_set():
call(print('Thread Loop 1'))
def loop2(self):
while not self.stop_threads.is_set():
call(print('Thread Loop 2'))
def combine(self):
self.stop_threads.clear()
self.thread1 = Thread(target = self.loop1)
self.thread2 = Thread(target = self.loop2)
self.thread1.start()
self.thread2.start()
def stop(self):
self.stop_threads.set()
self.thread1.join()
self.thread2.join()
self.thread1 = None
self.thread2 = None
if __name__ == '__main__':
master = tk.Tk()
master.title("Thread Start Stop Exercise")
master.geometry("1024x600")
control = Controller()
btn1 = Button(master, text="Start Thread", width=16, height=5, command=control.combine)
btn1.grid(row=2,column=0)
btn2 = Button(master, text="Stop Thread", width=16, height=5, command=control.stop)
btn2.grid(row=3,column=0)
master.mainloop()
【问题讨论】:
-
实际上你使用的是
tkinter.Event,而不是threading.Event,因为from tkinter import *这一行在from threading import Thread, Event之后。交换两条线。from tkinter import *不是导入 tkinter 的好习惯。 -
谢谢你,我知道我做的很愚蠢!非常感谢
标签: tkinter event-handling python-multithreading python-3.8