Can't figure out how to bind keys in tkinter
Hello, I've been doing some research on binding keys, but I can't figure out how to, the code for the key binds is on line 24, I've tried it with and without a while loop.
bind a key in
tkinter, you have to pass a function for it to call. Example:
def my_handler(): print("Something happened!") # tk stuff here... root.bind("some key", my_handler)
Notice how the handler is passed as
my_handler(). The former passes the function itself, the latter executes the function and uses the return value (
None) as the callback.
Your code passes parameters to
player.drive, and so you will have to wrap that function call in another function with no arguments. An easy way to do that is with lambda functions:
def normal_function(): print("Hello") lambda_function = lambda: print("Hello") normal_function() # "Hello" lambda_function() # "Hello"
So, here is your code: (lines 24 and 25)
root.bind("left arrow", lambda: player.drive(-1, 0)) root.bind("right arrow", lambda: player.drive(1, 0))