在线程内运行代码时遇到问题

时间:2021-03-22 19:09:40

标签: python tkinter backup python-multithreading

我正在编写一个脚本来备份我的文件,但我需要它在线程内运行。 代码运行良好,它完全符合我的需要。 我只需要它在一个线程内完成,我可以在需要时停止。 但是整个 GUI 冻结,直到它完成循环。 我对 python 比较陌生,而且我已经在这方面存货数周了。 我也很固执,不喜欢求助。

如果您需要更多上下文,如果他有 full script

import os
import threading
from time import sleep
import tkinter

root = tkinter.Tk()

# pathes to drives
sours = "path1"
buckup = "path2"


global stop_threads
stop_threads = False

# turns off the loop inside thread
def stop():
    global stop_threads
    stop_threads = True


def run():
    def backup(src, dst, ignore=None):

        # builds file stracher in back up folder
        if not os.path.exists(dst):
            os.makedirs(dst)

        for item in os.listdir(src):

            # stops the loop if true
            global stop_threads
            if stop_threads:
                break

            # joins pathe to copy too and from
            s = os.path.join(src, item)
            d = os.path.join(dst, item)

            # if the path dasent exist starts over
            if os.path.isdir(s):
                backup(s, d, ignore)
            else:
                # checks if file are in the folder if not copys tham
                if (
                    not os.path.exists(d)
                    or os.stat(s).st_mtime - os.stat(d).st_mtime > 1
                ):

                    sleep(5)  # debug
                    # copy2(s, d)
                    print("copying: ", s, "to: ", d)

    t1 = threading.Thread(target=backup(sours, buckup))
    t1.start()


button1 = tkinter.Button(root, height=3, width=30, text="stop", command=stop)
button1.grid(row=1, column=1)
button2 = tkinter.Button(root, height=3, width=30, text="Run", command=run)
button2.grid(row=1, column=2)


root.mainloop()

0 个答案:

没有答案
相关问题