Apr*_*an8 5 python multithreading tkinter
当 tkinter 根窗口关闭时,如何杀死已经运行的线程。我能够检测事件,但如果用户尚未启动任何线程,我在关闭窗口时会遇到错误。另外,当关闭时我是否能够检测到线程正在使用函数运行
self.thread.is_alive()
使用什么命令来杀死线程?
import threading
import tkinter as tk
from tkinter import messagebox
import time
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
self.master.title("myapp")
master.protocol("WM_DELETE_WINDOW", self.on_closing)
def createWidgets(self):
self.btn = tk.Button(self)
self.btn["text"] = "Start.."
self.btn.pack()
self.btn["command"] = self.startProcess
def startProcess(self):
self.thread = threading.Thread(target=self.helloWorld, args=("Hello World",))
self.thread.start()
def helloWorld(self, txt):
for x in range(5):
print (txt)
time.sleep(5)
def on_closing(self):
if messagebox.askokcancel("myapp", "Do you want to quit?"):
if self.thread.is_alive():
self.thread.stop()
self.master.destroy()
def main():
root = tk.Tk()
app = Application(master=root)
app.mainloop()
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2811 次 |
| 最近记录: |