Hayden B writes:

I am trying to code the bouncing red ball in Chapter 13 but the animation is not working. I have checked the code, and it makes sense, but I am getting these errors when I run:

RESTART: C:\Users\rf\AppData\Local\Programs\Python\Python36-32\Files .py\paddleball.py Traceback (most recent call last):   File "C:\Users\rf\AppData\Local\Programs\Python\Python36-32\Files .py\paddleball.py", line 33, in <module>     ball.draw()   File "C:\Users\rf\AppData\Local\Programs\Python\Python36-32\Files .py\paddleball.py", line 15, in draw     self.canvas.move(self.id, self.x, self.y)   File "C:\Users\rf\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 2585, in move     self.tk.call((self._w, 'move') + args) _tkinter.TclError: invalid command name ".!canvas"

...and the red ball gets "stuck" at the top "jiggling" but not bouncing or returning down as it is supposed to. I cannot figure out what the problem is. Can you help?

Your code is almost right, there's just one thing you've mistyped. Here's a snippet from my code:

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
tk.update()

And here's your code:

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
tk.update

Check the difference in the last line. Why do the missing brackets cause such a problem? The reason is that Python can't calculate the height of the canvas (400 pixels) until you call pack() and then update(). You are calling tk.update which is effectively just dumping information about the function, rather than calling the function itself. Here's what happens if I try that code:

>>> tk.update
<bound method Misc.update of <tkinter.Tk object .>>

And, because you aren't actually calling the update function, this line...

        self.canvas_height = self.canvas.winfo_height()

...actually results in canvas_height being 1 pixel, rather than 400. As a consequence, your ball then gets stuck jiggling at the top of the screen because both these if-statements end up being true:

        if pos[1] <= 0:
             self.y = 1
        if pos[3] >= self.canvas_height:
             self.y = -1

(so pos[1] ends up being less than or equal to 0, and pos[3] ends up being >= to the canvas_height)

By the way, you can ignore the error message -- that has nothing to do with your code. When you close the game window, your program is still trying to call the move function and so you get an error message because the canvas no longer exists (effectively).

Hope that helps.