我正在尝试编写一个程序,列出文件夹中的所有.xml文件,然后将它们复制到另一个目录并从原始目录中删除.这部分程序运行正常.我想这样做,以便我可以单击GUI中的按钮并让它扫描并处理文件夹,直到我按下按钮将其关闭.再次,打开它不是一个问题,但试图阻止它让我难过.我希望它等待一段时间,但使用time.sleep(x)冻结整个程序,不让我输入任何更多的命令,直到它停止睡眠,只有它处理,然后再次睡眠.关于如何从GUI tkinter按钮实质上启动/停止while循环的任何建议?

代码如下:

#! python3
import glob
import time
import shutil
import os
import sys
import datetime
import errno
import re
import fnmatch
import tkinter # copy tcl8.5 and tk8.5 to folder
from tkinter import ttk
import sched
flag = 0
with open("config.ini") as f:
g = f.readlines()
sourcedir = g[0][10:-1]
ICdir = g[1][13:-1]
BUdir = g[2][13:-1]
LOGdir = g[3][8:-1]
el = g[4][3:-1]
# reads directories from config.ini
h = len(sourcedir)
# obtains length of address, used later on
def exemel():
m = sorted(glob.glob(sourcedir+"/*.xml"), key=os.path.getmtime)
n = len(m)
if n == 0:
print("none left")
for item in range(n):
try:
m = sorted(glob.glob(sourcedir+"/*.xml"), key=os.path.getmtime)
n = len(m)
if n == 0:
print("none left")
global flag
if flag == 5:
flag = 0
item = item + 1
with FileLock(m[item]):
k = h - len(m[item])
g = m[item][k:]
shutil.copy(m[item], ICdir)
shutil.move(m[item], BUdir)
print(m[item] + " successfully processed.")
dated = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if os.path.exists(LOGdir):
with open(LOGdir, "a") as logging:
logline = '\n' + '"' + g[1:] + '", #' + dated + "# copied"
logging.write(logline)
else:
with open(LOGdir, "w") as logging:
logline = '"' + g[1:] + '", #' + dated + "# copied"
logging.write(logline)
except PermissionError:
print("File in use, waiting..")
time.sleep(1.5)
flag += 1
continue
except shutil.Error as e:
os.remove(ICdir + g)
os.remove(BUdir + g)
print("Existing files removed..")
dated = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if el == "1":
if os.path.exists(LOGdir):
with open(LOGdir, "a") as logging:
logline = '\n' + '"' + g[1:] + '", #' + dated + "# overwritten"
logging.write(logline)
else:
with open(LOGdir, "w") as logging:
logline = '"' + g[1:] + '", #' + dated + "# overwritten"
logging.write(logline)
except IndexError:
item = 0
continue
except SystemExit:
break
except KeyboardInterrupt:
break
def prunt():
print("ZES")
def config():
print("config")
def stop():
print("stop")
global x
x = False
global STOP
STOP = True
s = sched.scheduler(time.time, time.sleep)
def run_periodically(start, end, interval, func):
event_time = start
while event_time < end:
s.enterabs(event_time, 0, func, ())
event_time += interval
s.run()
def starter():
run_periodically(time.time(), time.time()+600, 60, exemel)
### GUI BEGIN ###
root = tkinter.Tk()
root.title("XML Wizard")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=("N","W", "E", "S"))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
sourceEntry = ttk.Entry(mainframe, width=50, textvariable=sourcedir)
sourceEntry.grid(column=2, row = 1, columnspan=2)
ttk.Label(mainframe, text="Source Directory:").grid(column=1, row=1, sticky="W")
BackupEntry = ttk.Entry(mainframe, width=50, textvariable=BUdir)
BackupEntry.grid(column=2, row = 2, columnspan=2)
ttk.Label(mainframe, text="Backup Directory:").grid(column=1, row=2, sticky="W")
ImportEntry = ttk.Entry(mainframe, width=50, textvariable=ICdir)
ImportEntry.grid(column=2, row = 3, columnspan=2)
ttk.Label(mainframe, text="Import Directory:").grid(column=1, row=3, sticky="W")
ttk.Button(mainframe, text="Go", command=starter).grid(column=4, row=5, sticky="W")
ttk.Button(mainframe, text="Save Config", command=config).grid(column=5, row=4, sticky="W")
ttk.Button(mainframe, text="Load Config", command=config).grid(column=5, row=3, sticky="W")
ttk.Button(mainframe, text="Stop", command=stop).grid(column=3, row=5, sticky="W")
root.mainloop()

FileLock函数在这里找到并且如果你想知道它可以完美地运行,但是我把它留给了空间/可读性.我知道我的代码很草率,但我只是刚刚开始编程.

任何建议/替代方法都非常欢迎!

顺便说一句:exemel是我想要循环的功能!

最佳答案 基本思想是拥有一个处理单个文件的函数,然后使用事件循环重复调用该函数,直到没有更多文件要处理.您可以使用after命令执行此操作.

在您的功能中,您还可以检查全局标志.如果设置了该标志,则该功能不起作用,并且不会安排任何工作.使用暂停按钮按钮设置标志.设置完成后,请调用您的函数一次,它将继续运行,直到处理完所有文件.

例如:

def do_one_file():
global files_to_process, paused
if not paused:
file = files_to_process.pop()
... do some work here ...
if len(files_to_process) > 0:
root.after(10, do_one_file)

这将检查您是否暂停了工作.如果还没有,它将从文件堆栈中提取一个文件来处理和处理它.然后,如果还有更多工作要做,它会在10ms内安排下一个要处理的文件.

假设实际工作只需几百毫秒,您的GUI将保持响应,并且“在后台”进行复制.我把它放在引号中因为它全部发生在主线程而不是后台线程或进程上,但它发生在GUI什么都不做的时候(实际上大部分时间都是这样).