我在Windows 10上的Python37中,在tkinter中工作,我编写了一个函数did_file_update
,该函数每10秒不断扫描一次桌面,以查看文件“ test.txt”是否已更改。还有一个函数abort_window_call
,该函数创建带有红色“ ABORT”按钮的窗口。我正在尝试编写一个脚本,该脚本将对这两个函数进行线程化,并允许我单击“ ABORT”按钮并在按下“ START”按钮并调用did_file_update
后终止该脚本。
import os
import time
import threading
import tkinter as tk
from tkinter import messagebox
import tkinter.messagebox as msg
from tkinter import Button, Message, Tk
global path_to_watch
path_to_watch = "C:\\Users\\Desktop"
class App():
def __init__(self):
pass
def abort_window_call(self):
abort_window = Tk()
abort_window.title("Would you like to abort?")
abort_window.geometry('50x90+200+200')
abort_button = tk.Button(abort_window, text='ABORT', font=('century gothic', 24),
bg='red', fg='white', height=1, width=5,
relief='raised', command=lambda: abort_window.destroy())
abort_button.pack(padx=10, pady=5)
abort_window.mainloop()
def did_file_update(self):
statinfo_before = os.stat("C:\\Users\\Desktop\\test.txt")
statinfo_size_before = statinfo_before.st_size
while 1:
time.sleep (10)
statinfo_after = os.stat("C:\\Users\\Desktop\\test.txt")
statinfo_size_after = statinfo_after.st_size
if statinfo_size_after != statinfo_size_before:
print("Updated: test.txt")
statinfo_size_before = statinfo_size_after
break
else:
pass
def main(self):
master = Tk()
ws = master.winfo_screenwidth()
hs = master.winfo_screenheight()
x = (ws/2) - (180)
y = (hs/2) - (70)
master.title("File Update")
master.geometry('360x140+%d+%d' % (x, y))
msg = Message(master, text = "FILE UPDATE", width=700)
msg.config(font=('century gothic', 28))
msg.grid(row=3, column=0)
start_button = tk.Button(master, text='START', font=('century gothic', 24),
bg='green', fg='white', height=1, width=17,
relief='raised', command=self.did_file_update)
start_button.grid(row=1, column=0, sticky='n', padx=10, pady=5)
master.mainloop()
app=App()
t = threading.Thread(target = app.abort_window_call)
t1 = threading.Thread(target = app.main)
t.start()
t1.start()
tl; dr 如何使abort_window_call
函数终止整个程序,即使在按下“ START”键和函数{{1 }}正在运行?