使用线程和tkinter模块在python中停止线程并避免“ RuntimeError”的最佳方法是什么?

萨米尔·阿曼(Samir Ahmane):

我已经在网络上经历了多个解决方案,但是它们需要大量代码,一旦您扩大规模,这些代码可能会造成混乱。是否有一种简单的方法可以停止线程并避免使用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()
萨米尔·阿曼(Samir Ahmane):

虽然这是完成事情的简单方法,但是用更少的代码行即可。我无法使用该.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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在JavaFX 8中管理多线程的最佳方法是什么?

用Java的并行线程写入文件的最佳方法是什么?

在Java中IPC的最佳方法是什么?

使用JasperReports的最佳方法是什么?

使用OnClick事件的最佳方法是什么?

在PyQt中,在主窗口和线程之间共享数据的最佳方法是什么

Python中在单独的线程中调用同一函数的最佳方法是什么?

使多个线程同时读取文件的最佳方法是什么?

从ESModules中的复杂路径导入模块的最佳方法是什么

在功能模块中声明服务的最佳方法是什么?

在node.js中执行“多线程”的最佳和有效方法是什么?

避免许多if语句的最佳方法是什么?

等待线程的最佳方法是什么?

在nodejs中运行单独线程的最佳方法是什么?

组织Python类的最佳方法是什么?

结合使用redux的最佳方法是什么?

Python:组织此线程的最佳方法是什么?

在nodejs中定义模块变量的最佳方法是什么?

做多线程的最佳方法是什么?

使用调用避免线程错误的正确方法是什么?

在后台执行任务的最佳方法是什么(application_start中的线程或调用方法)?

在日志中搜索的最佳方法是什么?

多线程的最佳方法是什么?

使用python字典时避免keyError的最佳方法是什么?

在intellij中导入新的python模块的最佳方法是什么?

使用线程和 tkinter 时出现 RuntimeError

理解和分析多线程代码的最佳方法是什么?

在 JAVA 8 中避免 ConcurrentModificationException 的最佳方法是什么

避免中间表的最佳方法是什么