Python Forum
problem with tkinter and multiprocessing
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem with tkinter and multiprocessing
#1
Hello,
I want to run several program at the same time in a tkinter window, but each process that I launch reopen an other tkinter window. Here is a simplified code that give the same error :

from multiprocessing import Process
from tkinter import *

def f1():
    print(1)

def f2():
    print(2)

def main():
    p1 = Process(target=f1)
    p1.start()
    p2 = Process(target=f2)
    p2.start()
    p1.join()
    p2.join()

window = Tk()
if __name__ == '__main__':
    main()
window.mainloop()
How can I avoid this problem ?
Reply
#2
When you start a process the process loads the module (at least in Windows). This runs "window = Tk()" for each process. Protect the tkinter code behind the if __name__ == '__main__'. I think in Linux/Unix processes are spawned using "fork" and it inherits knowledge about the module instead of having to reload the code. I think you program would run differently under Linux or on a Mac. The code below should work everywhere.
from multiprocessing import Process
from tkinter import *
 
def f1():
    print(1)
 
def f2():
    print(2)
 
def main():
    p1 = Process(target=f1)
    p1.start()
    p2 = Process(target=f2)
    p2.start()
    p1.join()
    p2.join()
 
if __name__ == '__main__':
    window = Tk()
    main()
    window.mainloop()
Reply
#3
Thanks, it work now !
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020