Skip to content
← Back to Community
Can't figure out how to bind keys in tkinter
Profile icon
Dunce

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.

Answered by 19wintersp [earned 5 cycles]
View Answer
Voters
Profile icon
15jcherian
Profile icon
Dunce
Comments
hotnewtop
Profile icon
19wintersp

When you 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, not 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"

It's like a normal function, except shorter and anonymous: they are the equivalent of arrow functions in JavaScript, for example.

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))
Profile icon
Dunce

@19wintersp Ok, thanks allot! :-)