【发布时间】:2020-01-13 10:15:22
【问题描述】:
我创建了一个带有“停止”按钮的 GUI。当 GUI 运行时,另一个模块被调用,其中包含一个用于后台函数的 while 循环。停止按钮将用于将变量传递给循环以停止它。但是,当调用包含循环的模块时,GUI 会冻结。我考虑过使用“线程”库,但找不到任何 tkinter 特定内容。任何关于如何创建代码的建议或小例子都会有很大帮助。
【问题讨论】:
标签: python multithreading tkinter
我创建了一个带有“停止”按钮的 GUI。当 GUI 运行时,另一个模块被调用,其中包含一个用于后台函数的 while 循环。停止按钮将用于将变量传递给循环以停止它。但是,当调用包含循环的模块时,GUI 会冻结。我考虑过使用“线程”库,但找不到任何 tkinter 特定内容。任何关于如何创建代码的建议或小例子都会有很大帮助。
【问题讨论】:
标签: python multithreading tkinter
这是一个带有 2 个按钮的基本 GUI,可以启动和停止一个线程,该线程会增加一个变量 count。
我让你试试:
import tkinter as tk
import threading
import time
class GUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("test")
self.button_start = tk.Button(self, text="Start", command=self.start_thread)
self.button_start.pack()
self.button_stop = tk.Button(self, text="Stop", command=self.stop_thread)
self.button_stop.pack()
self.count = 0
self.continue_thread = True
def start_thread(self):
self.count = 0
self.continue_thread = True
self.t1 = threading.Thread(target = self.counter)
self.t1.daemon = True # With this parameter, the thread functions stops when you stop the main program
self.t1.start()
def stop_thread(self):
self.continue_thread = False
self.t1.join()
def counter (self):
while self.continue_thread:
print("i =", self.count)
self.count += 1
time.sleep(1)
if __name__ == "__main__":
app = GUI()
app.mainloop()
【讨论】:
这只是一个示例程序,用于说明如何杀死正在运行的线程。
import threading
import time
def run():
while True:
print('thread running')
global stop_threads
if stop_threads:
break
if __name__=="__main__":
stop_threads = False
t1 = threading.Thread(target = run) ##background loop
t1.start()
time.sleep(1)
#while clicking on the button in GUI kill the thread like this
stop_threads = True
t1.join()
print('thread killed')
【讨论】: