当 运行 线程中的函数时,Tkinter 正在打开新的 windows
Tkinter is opening new windows when running a function in a thread
大家好,我正在使用 python 2.7.15 和 tkinter。它是一个带有一些按钮的简单 GUI。按下按钮后,我需要在线程中启动一个函数(我不需要打开任何新的 windows)。
发生的情况是为每个线程打开一个新的程序 GUI 副本。有没有什么方法可以在不弹出 Tkinter gui 的新副本的情况下启动一个函数(进行一些计算)?
我正在制作这样的帖子:
thread = Process(target=functionName, args=(arg1, arg2))
thread.start()
thread.join()
编辑:这里是一些要重现的代码。如您所见,下面 "sample" 我感兴趣的只是 运行 一个函数。不要克隆整个程序。
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()
谢谢。
由于子进程会继承父进程的资源,也就是说它会继承父进程的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()
大家好,我正在使用 python 2.7.15 和 tkinter。它是一个带有一些按钮的简单 GUI。按下按钮后,我需要在线程中启动一个函数(我不需要打开任何新的 windows)。
发生的情况是为每个线程打开一个新的程序 GUI 副本。有没有什么方法可以在不弹出 Tkinter gui 的新副本的情况下启动一个函数(进行一些计算)?
我正在制作这样的帖子:
thread = Process(target=functionName, args=(arg1, arg2))
thread.start()
thread.join()
编辑:这里是一些要重现的代码。如您所见,下面 "sample" 我感兴趣的只是 运行 一个函数。不要克隆整个程序。
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()
谢谢。
由于子进程会继承父进程的资源,也就是说它会继承父进程的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()