I am a beginner python learner, tkinter in particular.
I want to make a 'loading screen' of a simple python script and closes after the script ends.
But making a window requires a mainloop
function which means that it will loops infinitely or wait for a user interaction(or so i think) and it will eliminate the idea of a 'loading' screen.
I tried something but ends up with (Put Loading Screen) -> (Loading screen still have mainloop
) -> (Can't Run Script because of waiting)
What i wanted in detail was (Put Loading Script) -> (Run Script) -> (Script ends) -> (Loading Screen destroy)
I got a lot of experience in other languages especially Java but java can just declare a frame -> run other things afterwards -> call a frame.dispose()
and that's just it. Any tips or suggestions for a learner?
EDIT: The script actually is a image processing algorithm that connects to a database and I can't just put a timed wait or sleep since the database can be expanded and it might be take longer than the allocated time.
Something along these lines might work for you. This creates the window root
, and defines a function task
which destroys root
as the last thing it does. In this example, task
just sleeps for two seconds, but you'd replace that sleep
call with whatever code you want to run.
You put the task
function into the main loop event queue with root.after(200, task)
. This means the code will first create the root
window, wait 200 milliseconds, then call task()
, which sleeps for two seconds and destroys the window. At least for this example you need the 200 millisecond delay so that the main loop has enough time to draw the window before the sleep
call halts everything (the number might be different for you; increase it if the window doesn't draw properly).
import tkinter as tk
from time import sleep
def task():
# The window will stay open until this function call ends.
sleep(2) # Replace this with the code you want to run
root.destroy()
root = tk.Tk()
root.title("Example")
label = tk.Label(root, text="Waiting for task to finish.")
label.pack()
root.after(200, task)
root.mainloop()
print("Main loop is now over and we can do other stuff.")
Edit: Added a comment to the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With