您应该使用threading 模块。我给你写了一点代码。 background 函数可以在单独的线程上启动您的函数。
如果你的函数有输入参数,你可以像这样传递它们:command=lambda : background(print_numbers, (50,)))。重要提示:args 必须是一个元组,即使它只有一个
代码:
import tkinter as tk
from tkinter import ttk
import threading
import time
root = tk.Tk()
root.geometry("510x200")
def getFolderPath():
print("getFolderPath. Thread: {}".format(threading.get_ident()))
time.sleep(10)
def down():
print("Down. Thread: {}".format(threading.get_ident()))
def background(func, args):
th = threading.Thread(target=func, args=args)
th.start()
btnFind = ttk.Button(root, text="Browse Folder", command=lambda: background(getFolderPath, ()))
btnFind.place(x=0, y=0)
dwn = ttk.Button(root, text="Download", width="25", command=lambda: background(down, ()))
dwn.place(x=190, y=120)
root.mainloop()
获取窗口:
控制台输出:(如果您点击按钮)
>>> python3test_file.py
Down. Thread: 140212479096576
Down. Thread: 140212479096576
getFolderPath. Thread: 140212479096576
getFolderPath. Thread: 140212468516608
getFolderPath. Thread: 140212460123904
Down. Thread: 140212451731200
getFolderPath. Thread: 140212451731200
Down. Thread: 140212443338496
你可以看到线程的ID是不同的。这意味着任务在不同的线程上运行。