我在python中有两个函数,一个来自外部py文件,另一个作为Tkinter GUI函数。我希望能够同时运行两者,而不必停止运行GUI或停止运行外部功能。我尝试过线程,但是它只运行我首先声明的线程。这是来自GUI文件的代码:
import bot
import tkinter as tk
def tasks():
tsks = tk.Tk()
tsks.title("Tasks")
tsks.geometry("250x600")
Label(tsks, text='Label stuff').pack(side = 'top')
if pressed == True:
a0 = Label(tsks, text='more label stuff').pack()
tsks.mainloop()
def press():
global pressed
pressed=True
Thread(target = tasks()).start()
Thread(target = bot.on()).start()
tasks()
press()
答案 0 :(得分:0)
您可以使用multiprocessing.Process
。例如
from multiprocessing import Process
from time import sleep
def s1():
count = 10
while count >= 0:
print('This is s1.')
sleep(1.)
count -= 1
def s2():
count = 5
while count >= 0:
print('This is s2.')
sleep(1.)
count -= 1
p1 = Process(target=s1, daemon=True)
p2 = Process(target=s2, daemon=True)
p1.start(), p2.start()
p1.join(), p2.join()
您可以运行此脚本,然后查看两个功能正在同时运行。