在线程中运行函数时,Tkinter正在打开新窗口

时间:2019-02-19 22:03:18

标签: python multithreading tkinter python-multithreading

大家好,我正在使用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()

谢谢。

1 个答案:

答案 0 :(得分:2)

由于子进程将从父进程继承资源,这意味着它将从父进程继承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()