繁体   English   中英

在小部件启动的进程正在运行时,如何在Tkinter小部件中运行计时器?

[英]How do I make a timer run in a Tkinter widget while a process, started by the widget, is running?

因此,我使用Tkinter创建了一个小部件,允许用户输入一些信息并单击运行按钮,这将开始运行在其他地方定义的测试。 这是代码。 它远非完美,这只是一个原型:

from tkinter import*
import controller
root = Tk()
#create labels
label = Label(text = "text you don't need to know")
label.pack()
remind = Label(text = "more text you don't need to know")
remind.pack()

#create text fields
name = Entry(root)
name.pack()
name.insert(0, "Name")
name.focus_set()
testName = Entry(root)
testName.pack()
testName.insert(0, "Test name")
duration = Entry(root)
duration.pack()
duration.insert(0, "Duration in minutes")


def runTest():
    controller.main(testName.get(), name.get(), float(duration.get()))

#create run button
run = Button(root, text = "Run", fg = "red", width = 10, command = runTest)
run.pack()

root.mainloop()

所以,这是我的问题。 该项目一旦实施,工期可能会定为1-4小时。 因此,我想做的是在小部件上显示一个倒计时,以便用户可以随时引用该计时器以查看生成数据的时间。 问题在于,一旦我的测试开始运行,小部件就会锁定,直到完成为止。 我尝试过的所有内容都将搁置,直到完成测试运行,然后再执行我想要的操作。 那时并没有太大帮助。

有人在实现这样的事情上有经验吗? 谢谢。

您需要在runTest完成工作。 threading模块将是您的朋友(例如from threading import Thread )。

然后重写您的runTest方法:

def runTest():
    # pack your arguments in a tuple
    mainArgs = (testName.get(), name.get(), float(duration.get()))
    # create a thread object armed with your function and the args to call it with
    thread = Thread(target=controller.main, args=mainArgs)
    # launch it
    thread.start()
    #and remember, never set state (directly or indirectly) from separate threads without taking appropriate precautions!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM