【问题标题】:How can I run my python script while a Tkinter GUI is active?如何在 Tkinter GUI 处于活动状态时运行我的 python 脚本?
【发布时间】:2013-03-09 18:48:30
【问题描述】:

我正在尝试创建一个 GUI。我需要在 GUI 处于活动状态时执行另一个 python 脚本。 (GUI 应该处理来自此执行的数据)因为我使用 Tkinter 创建了 GUI,所以我无法在 python 终端中执行另一个文件。

我该如何解决这个问题?

【问题讨论】:

  • python 有分叉的舌头
  • @stark 需要帮助,因为我是 python 的初学者..
  • 这似乎是一个类似的问题:stackoverflow.com/questions/459083/…>
  • @stark 你能解释一下吗,或者你能举个例子。对上述问题的回答让我感到困惑......

标签: python python-3.x tkinter


【解决方案1】:

您不需要启动另一个解释器。

您可以简单地在单独的线程或进程中执行来自其他脚本的代码。


重构你的“其他”脚本

您希望您的“其他”脚本可以从另一个脚本中调用。为此,您只需要一个函数来执行您的脚本曾经执行的操作。

#other.py

def main(arg1, arg2, arg3):
    do_stuff(arg1, arg2)
    more_stuff(arg2, arg3)
    other_stuff(arg1, arg3) 
    finish_stuff(arg1, arg2, arg3)

在另一个线程中执行代码

在你的主脚本中,当你想从other.py执行代码时,启动一个新线程:

 #script.py

 from threading import Thread

 from other import main

 thread = Thread(target = main)
 thread.start() # This code will execute in parallel to the current code

要检查您的工作是否完成,请使用thread.is_alive()。要阻止直到完成,请使用thread.join()

【讨论】:

猜你喜欢
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-24
相关资源
最近更新 更多