0

My code should create a window and then count from 1 to 10 but, it makes a window and only counts from 1 to 10 when you close the window. how do I make it count when the window pops up, not when it closes?

from tkinter import Tk, mainloop import time I = 1 window = Tk() window.title("Game") window.configure(width=500, height=300) window.configure(bg='blue') window.geometry("+" + str(I * 5) + "+0") window.mainloop() while I < 10: print(I) print("Hi") I += 1 time.sleep(0.2) 
2
  • Just move the count code right before the window creation? Commented Oct 1, 2022 at 6:49
  • @comodoro the goal is to first make the window pop up then start the counting code but the window pops up then the code stops until I close the newly made window Commented Oct 1, 2022 at 6:52

2 Answers 2

1

The while loop in your code only runs after the window.mainloop() (after it has ended).

This code seems to work:

from tkinter import Tk I = 1 window = Tk() window.title("Game") window.configure(width=500, height=300) window.configure(bg='blue') window.geometry("+" + str(I * 5) + "+0") def loop(): global I print(I) print("Hi") I += 1 window.after(200, loop) loop() window.mainloop() 

The window.after() method is used to run some kind of loops even when the mainloop is running.

Sign up to request clarification or add additional context in comments.

Comments

0

What mainloop does is start using the main thread for GUI events and nothing else; that's why your counting code starts only after closing the window. If you want to execute code while the GUI is running, you can use the after method:

from tkinter import Tk, mainloop import time I = 1 # Wrap the code in a standalone method def count(): # In order to access a global variable from a method global I while I < 10: print(I) print("Hi") I += 1 time.sleep(0.2) window = Tk() window.title("Game") window.configure(width=500, height=300) window.configure(bg='blue') window.geometry("+" + str(I * 5) + "+0") # In order to have the window rendered already window.update() # Execute code on the main thread window.after(0, count) window.mainloop() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.