因此,我为tkinter的新生事物制作了名为duinocoin的硬币的gui矿工。 因此,我将挖掘功能集成到功能中,因此当您按下按钮时,它就会进行挖掘。问题是当我单击我的我无法单击任何其他按钮,因为它在该挖掘循环中。我该如何解决?
-Eth guy
答案 0 :(得分:1)
使用input$cli
与UI线程创建单独的线程:
threading
看一下这个例子,首先运行循环按钮,然后按下下一个按钮,您会注意到,它在from tkinter import *
from threading import Thread
from time import sleep
root = Tk()
def run(): #the loop function
b1.config(command=Thread(target=run).start) #or b1.config(state=DISABLED)
while True:
print('Hey')
sleep(2) #pause for 2 seconds.
def step(): #the in between function
print('This is being printed in between the other loop')
b1 = Button(root,text='Loop',command=Thread(target=run).start)
b1.pack()
b2 = Button(root,text='Separate function',command=step)
b2.pack()
root.mainloop()
循环之间执行。但是while
可能仍会冻结您的GUI。
说明:
线程处理没什么,就像普通线程一样,想象一下汽车经过一个线程而发生事故,因此该线程可能会中断,就像那样,您的tkinter在一个线程上运行,而您的sleep()
循环也在运行导致线程冻结,但是使用while
时,您为while函数创建了一个新线程,因此带有tkinter的线程运行得很顺利,而带有threading
循环的线程被冻结了,没关系用于其他线程。
或者,您也可以为此目的使用while
,例如:
after()
在这里,当您按下循环按钮时,它将开始循环,当您按下单独的按钮时,它将在伪循环之间打印一个功能,而当您按下停止时,它将停止循环。
from tkinter import *
from threading import Thread
from time import sleep
root = Tk()
def run():
global rep
print('Hey')
rep = root.after(2000,run) #run the same function every 2 seconds
def stop():
root.after_cancel(rep)
def step():
print('This is being printed in between the other loop')
b1 = Button(root,text='Loop',command=run)
b1.pack()
b2 = Button(root,text='Seperate function',command=step)
b2.pack()
b3 = Button(root,text='Stop loop',command=stop)
b3.pack()
root.mainloop()
方法主要接受两个参数:
after()
-该函数的运行时间ms
-给定ms结束后要运行的函数。func
仅采用after_cancel()
的变量名。希望您能更好地理解,如果您有任何疑问或错误,请告诉我。
欢呼