0

I am trying to make a ball go to one side of the screen turn around, then come back. Whenever I try running this program the tkinter window doesn't show up, but when i get rid of the sleep(0.5) part it shows up when the ball is already off the screen. Can someone tell my what I did wrong?

from tkinter import *
from time import sleep

window = Tk() 
cWidth = 800
cHeight = 500
c = Canvas(window, width = cWidth, height = cHeight, bg='black')
c.pack()
x = 400
y = 250
ball = c.create_polygon(x, y, x, y+25, x+25, y+25, x+25,y, fill='yellow')


Ball_move = 10

for i in range(200):
    c.move(ball, Ball_move, 0)
    window.update
    x += Ball_move
    if x == cWidth:
        Ball_move = -Ball_move
    sleep(0.5)

window.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
john
  • 11
  • 1
  • 2
    http://stackoverflow.com/questions/10393886/python-time-sleep Check this one please. – Lafexlos Jun 16 '16 at 13:53
  • 2
    Also relevant http://stackoverflow.com/questions/30284270/why-does-time-sleep-pause-tkinter-window-before-it-opens and http://stackoverflow.com/questions/33175457/time-sleep-equivalent-on-tkinter – PM 2Ring Jun 16 '16 at 13:56
  • 1
    I would throw `window.update()`into the ring ;-) .. instead of `window.update` (without the parens) - in addition to the other hints on not using `time.sleep(...)` in tkinter eventloops ... – Dilettant Jun 16 '16 at 13:57
  • 1
    Well spotted, @Dilettant. :) However, that shouldn't be necessary once `sleep` is removed and the `.after` method is used to get the desired delay. – PM 2Ring Jun 16 '16 at 14:00
  • FWIW, here's a very simple demo of Tkinter animation with a time delay: http://stackoverflow.com/a/32766256/4014959 – PM 2Ring Jun 16 '16 at 14:01
  • An infinite loop is not the right way to do animation with tkinter. See http://stackoverflow.com/a/11505034/7432 – Bryan Oakley Jun 17 '16 at 20:27

1 Answers1

0

In windows, Tkinter frame shows up only after you call mainloop(). In your case, the for loop might be blocking it. Keep the for loop in a function and then call that function using threads so that it won't block the main loop.

gwthm.in
  • 638
  • 9
  • 24