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

时间:2014-06-27 18:57:03

标签: python tkinter

因此,我使用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小时。因此,我想要做的是在小部件上显示倒计时,因此用户可以随时引用该计时器以查看生成数据的时间。问题是,一旦我的测试运行,小部件就会锁定,直到它完成。我尝试的所有东西都被搁置,直到它完成测试,然后它做了我想要的。在那一点上它没有多大帮助。

有人在实施这样的事情方面有一些经验吗? 感谢。

1 个答案:

答案 0 :(得分:1)

您需要在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!