【问题标题】:Tkinter is opening new windows when running a function in a thread在线程中运行函数时,Tkinter 正在打开新窗口
【发布时间】:2019-02-19 22:03:18
【问题描述】:

大家好,我正在使用 python 2.7.15 和 tkinter。它是一个带有一些按钮的简单 GUI。按下按钮后,我需要在线程中启动一个函数(我不需要打开任何新窗口)。

正在发生的情况是,每个线程都会打开一个新的 GUI 程序副本。有没有办法在不弹出 Tkinter gui 的新副本的情况下启动一个函数(进行一些计算)?

我正在做一个这样的线程:

thread = Process(target=functionName, args=(arg1, arg2))
thread.start()
thread.join()

编辑:这是一些要重现的代码。如您所见,我对“示例”下面的所有兴​​趣都是运行一个函数。不要克隆整个程序。

from Tkinter import *
from multiprocessing import Process

window = Tk()

window.title("Test threadinng")

window.geometry('400x400')


def threadFunction():
    sys.exit()

def start():
    thread1 = Process(target=threadFunction)
    thread2 = Process(target=threadFunction)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

btn = Button(window, text="Click Me", command=start, args=())

btn.grid(column=1, row=1)

window.mainloop()

谢谢。

【问题讨论】:

  • 如果没有看到functionName 的定义,我们不知道为什么它会弹出一个新窗口——你能创建一个Minimal, Complete, and Verifiable example 吗?它不一定是您的真实代码,只要是仍能重现您的问题的最少代码即可。
  • multiprocessing.Process 不是线程。这是一个过程。你打算使用threading.Thread吗?
  • @RandomDavis(已编辑和添加)
  • @StevenRumbalski 我相信线程很慢?我对它进行了一些尝试,线程将在同一个 CPU 内核上运行所有线程。我需要它快速(进行大量计算),最终我不在乎我使用的是线程还是进程,以更快的速度解析数百个文件。我是 python 和 Tkinter 的新手,所以请原谅我对这个主题的无知。我遇到的问题是 Windows 打开了使用 Process 的副产品并且没有办法解决吗?

标签: python multithreading tkinter python-multithreading


【解决方案1】:

由于子进程将从父进程继承资源,这意味着它将从父进程继承 tkinter。将 tkinter 的初始化放在 if __name__ == '__main__' 块内可能会解决问题:

from tkinter import *
from multiprocessing import Process
import time

def threadFunction():
    print('started')
    time.sleep(5)
    print('done')

def start():
    thread1 = Process(target=threadFunction)
    thread2 = Process(target=threadFunction)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

if __name__ == '__main__':
    window = Tk()
    window.title("Test threadinng")
    window.geometry('400x400')
    btn = Button(window, text="Click Me", command=start)
    btn.grid(column=1, row=1)
    window.mainloop()

【讨论】:

  • 就是这样!谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多