我已经在网络上经历了多个解决方案,但是它们需要大量代码,一旦您扩大规模,这些代码可能会造成混乱。是否有一种简单的方法可以停止线程并避免使用RuntimeError: threads can only be started once
,以便无限次调用该线程。这是我的代码的简单版本:
import tkinter
import time
import threading
def func():
entry.config(state='disabled')
label.configure(text="Standby for seconds")
time.sleep(3)
sum = 0
for i in range(int(entry.get())):
time.sleep(0.5)
sum = sum+i
label.configure(text=str(sum))
entry.config(state='normal')
mainwindow = tkinter.Tk()
mainwindow.title('Sum up to any number')
entry = tkinter.Entry(mainwindow)
entry.pack()
label = tkinter.Label(mainwindow, text = "Enter an integer",font=("Arial",33))
label.pack()
print(entry.get())
button = tkinter.Button(mainwindow, text="Press me", command=threading.Thread(target=func).start)
button.pack()
虽然这是完成事情的简单方法,但是用更少的代码行即可。我无法使用该.join()
方法。但是,该应用似乎没有创建任何新线程。这通过threading.active_counts()
方法是显而易见的。这是下面的代码:
import tkinter, threading, time
def calc():
entry.config(state='disabled')
label.configure(text="Standby for 3 seconds")
time.sleep(3)
sum = 0
for i in range(int(entry.get())):
time.sleep(0.5)
sum = sum+i
labelnum.configure(text=str(sum))
button.config(state='normal')
label.configure(text="Sum up to any number")
entry.config(state='normal')
def func():
t = threading.Thread(target=calc)
t.start()
#del t
print('Active threads:',threading.active_count())
mainwindow = tkinter.Tk()
mainwindow.title('Sum up to any number')
entry = tkinter.Entry(mainwindow)
entry.pack()
label = tkinter.Label(mainwindow, text = "Enter an integer",font=("Arial",33))
label.pack()
labelnum = tkinter.Label(mainwindow, text="",font=('Arial',33))
labelnum.pack()
button = tkinter.Button(mainwindow, text="Press me", command=func)
button.pack()
mainwindow.mainloop()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句