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

2024-04-26 19:10:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我正在做一条这样的线:

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

编辑:这里有一些代码要复制。如您所见,我对下面的“示例”感兴趣的是运行一个函数。不是为了克隆整个程序。在

^{pr2}$

谢谢。在


Tags: 函数程序targettkinter副本情况gui线程
1条回答
网友
1楼 · 发布于 2024-04-26 19:10:25

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

相关问题 更多 >