代码之家  ›  专栏  ›  技术社区  ›  Duxa

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

  •  0
  • Duxa  · 技术社区  · 6 年前

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

    非常感谢。

    0 回复  |  直到 6 年前
        1
  •  3
  •   acw1668    6 年前

    由于子进程将从父进程继承资源,这意味着它将从父进程继承tkinter。把tkinter的初始化放在里面 if __name__ == '__main__' block可以解决这个问题:

    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()