Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to continue programm after closing tkinter-window in python?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading