Search code examples
pythontkintergame-developmentkeystrokes

How to use keys to influence movements on a window in python


I am relatively new to programming and I've gotten into attempting to recreate classic arcade games to increase my knowledge of programming. Right now I'm trying to re-create Pong. I have created all the necessary animations for the game, but i have no idea how to assign key strokes. In the end I want to be able to press up and have my character and pong move up. How do I do this in Tkinter, or can I? if I can't do it in Tkinter what can I use to re-create this game?


Solution

  • The way to attach behavior to keys with with bindings. For example, assuming you have a canvas widget where you are doing your animations. If you want the up arrow key to call a function such as to change the direction of the paddle, you would create a binding like this:

    def move_up(event):
        <put your "move up" code here>
    
    the_canvas.bind("<Up>", move_up)
    

    This will cause the move_up function to be called every time the user presses the "up" arrow key.

    There are many places on the internet to learn about bindings. Tkdocs.com is one such site. A tutorial on bindings can be found here: http://www.tkdocs.com/tutorial/concepts.html#events