【问题标题】:Is there any way to pause and resume thread in Tkinter?有没有办法在 Tkinter 中暂停和恢复线程?
【发布时间】:2020-12-26 17:54:42
【问题描述】:

我通常使用以下命令启动线程,

threading.Thread(target=function_name).start()

有什么办法可以暂停一下

threading.Thread(target=name).wait()

简历就像

threading.Thread(target=name).set()

【问题讨论】:

  • 这能回答你的问题吗? Thread that I can pause and resume?
  • 我也看到了,但不幸的是,我认为这不是最好的方法,例如当你想停止处理大量数据而不是循环的函数时
  • 您需要使用变量来设置信号,因此线程会每隔一段时间检查变量,然后根据变量的值停止、等待或启动。

标签: python python-3.x multithreading tkinter


【解决方案1】:

检查this 项目怎么样。该项目满足您的所有要求。 Python 的内置线程模块暂时不支持播放和暂停功能。

所以要安装这些模块:pip install pythreadworker

这里是安装后的例子:

from worker import Worker  # We import the Worker to create thread

def some_long_running_task(foo, bar, tee="foo"):
    do_random_long_stuff()
    # ...

if __name__ == '__main__':
    # to make a thread we initialise Worker or somewhat so called the Thread of threading module
    thread = Worker(some_long_running_task)  # remember just pass the function without execution parenthesis

    # Now to start thread while also supplying arguments, we call start method
    thread.start("bar", bar="foo", tee=123)

    # To pause a the thread we use pause method
    thread.pause()

    # To resume it we use resume method
    thread.resume()

    # To use the Thread.join Worker class, use the join method
    thread.join()

    # And to kill it we use 
    thread.stop()

但是如果你使用time.sleep,请记住使用它 那么你将不得不用worker.sleep替换它

所以例如你导入的代码是

from time import sleep

替换为

from worker import sleep

希望这会有所帮助。

【讨论】:

  • 感谢您的建议!我浏览了这个项目,但用法很混乱..例如,如果我想在threading.Thread(target=function_name).start()这样的线程中执行单个函数,那么这个项目中的场景是什么?
  • 希望对您有所帮助
【解决方案2】:

线程模块有一个信号量,这可能会有所帮助。如果线程模块中还没有内置的东西,您可以尝试使用特定于每个线程的 Tkinter 信号量变量,并让线程在某个轮询循环中检查其信号量。

【讨论】:

    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2021-09-12
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    相关资源
    最近更新 更多