0

I got a problem with two tkinter windows which I simplified as follows:

import tkinter as tk

def function_2(): # creates Window 2
    root2 = tk.Tk()
    # some buttons targeting other functions
    root2.mainloop()
    print(1) # just a placeholder for some other code

def function_1(): # creates Window 1
    root = tk.Tk()
    funtcion_2()
    root.mainloop()

function_1()

I want the "print(1)" in function_2 to be executed after I close window 2, which is created in function_2, manually by clicking the X in the upper right corner of a Windows windows. However the output "1" won't show up as long as I don't close window 1 as well. What shall I do to get the desired result?

Thanks in advance!

I already tried Threading cause I thought the code in function_2 seems to 'wait' until everything in function_1 is executed. I also tried

root2.protocol("WM_DELETE_WINDOW", lambda: root2.destroy())

underneath the line

root2 = tk.Tk()

in function_2. But the result is the same: I don't return to function_1 after closing window 2.

Agent00111
  • 35
  • 4
  • That print should already be executed before the function1's mainloop, so I assume it could be buffering issue? Print is not flushing by default (although usually something else triggers the flushing). Try `print(1, flush=True)` – h4z3 Jul 27 '23 at 07:41
  • @h4z3 thanks for your comment but even if this works, the "print(1)" command is just an example for some other code. – Agent00111 Jul 27 '23 at 07:47

1 Answers1

2

It is recommended that mainloop() should be called once. Also avoid using multiple instances of Tk().

For your case, use root2.wait_window() instead of root2.mainloop():

def function2(): # creates Window 2
    root2 = tk.Tk()
    # some buttons targeting other functions
    root2.wait_window() # wait for closing of root2
    print(1)

Note that there are typos in your code:

  • function_1() should be function1() or vice versa
  • function_2() should be function2() or vice versa
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • Thank you very much! It works! I fixed the typos, thanks for mentioning. What should I do instead of using multiple instances of Tk()? How can I create multiple windows in a nicer way? And whats wrong with this in the first place? – Agent00111 Jul 27 '23 at 07:56
  • See [why-are-multiple-instances-of-tk-discouraged](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged) – acw1668 Jul 27 '23 at 09:02