valcarcexyz
valcarcexyz

Reputation: 622

Tkinter TopLevel not showing when it's supposed to

I have a very simple python code: a tkitner button that process some images in the background. I wanted to open a tkinter toplevel to show the user that it was doing something, but for my surprise is not working as I thought it would. The command on the tk.Button is the next method:

def processing(self):
        """Starts the images processing"""
        # Open a Tk.Toplevel
        aux_topLevel = Splash(self.window) # a simple Tk.Toplevel class, that works perfectly
        self._process_images() # starts processing the images
        # I wanted to kill here the topLevel created before
        aux_topLevel.destroy()

My surprise: the window is displayed once the processing images is done (tried it out adding prints and time.sleep), however, i couldn't display the TopLevel when I wanted to.

Is there anything am I doing wrong? Any help is appreciated. Thank you.

Upvotes: 2

Views: 1362

Answers (1)

scotty3785
scotty3785

Reputation: 7006

Consider the following example and try to run it.

What you'd think should happen is that the new Toplevel window should open, some event happens for a period of time and then the window is destroyed.

What actually happens is the window is opened, but never displayed, the task occurs and then the window is destroyed.

from tkinter import *
import time

def processing():
    new = Toplevel(root)
    new.geometry("200x150")
    lbl = Label(new,text="--")
    lbl.grid()
    for i in range(50):
        time.sleep(0.1)
        #Un-comment the line below to fix
        #root.update()
        print(i)
        lbl['text'] = "{}".format(i)
    new.destroy()

root = Tk()
root.geometry('200x100')
btnGo = Button(root,text="Go",command=processing)
btnGo.grid()
root.mainloop()

If you un-comment out the root.update() line and re-run the code, the window will be displayed.

There are better ways to deal with tasks that takes a while to process, such as threading.

Upvotes: 3

Related Questions