Key Binding in Tkinter is a valuable still that will help you in creating complex GUI applications. The concept is simple. You “bind” a specific Key, or type of key to a functions that executes when that key is pressed.
The below code demonstrates how to use almost all of the main key bindings in Tkinter. We have a small breakdown and code explanation here in this tutorial, but I do recommend you check out our Video Tutorial for Tkinter Key Bindings. In it, we recreate the below code from scratch, explaining each step in detail along the way.
import tkinter as tk class MainWindow: def __init__(self, master): self.master = master self.usernames = ["Player1", "CodersLegacy", "Knight"] self.frame = tk.Frame(self.master, width = 300, height = 300) self.frame.pack() self.label = tk.Label(self.frame, text = "This is some sample text") self.label.place( x = 80, y = 20) self.button = tk.Button(self.frame, text = "Button") self.button.place( x = 120, y = 80) self.entry = tk.Entry(self.frame) self.entry.place( x = 80, y = 160) self.entry2 = tk.Entry(self.frame) self.entry2.place( x = 80, y = 200) self.bindings() def bindings(self): self.master.bind('a', lambda event: print("A was pressed")) self.frame.bind('<Enter>', lambda event: print("Entered Frame")) self.label.bind('<Button-1>', lambda event: print("Mouse clicked the label")) self.button.bind('<Enter>', lambda event: self.color_change(self.button, "green")) self.button.bind('<Leave>', lambda event: self.color_change(self.button, "black")) self.entry.bind('<Key>', lambda event: self.pass_check()) self.entry.bind('<FocusIn>', lambda event: self.Focused_entry()) self.entry.bind('<FocusOut>', lambda event: self.UnFocused_entry()) def color_change(self, widget, color): widget.config(foreground = color) def pass_check(self): text = self.entry.get() for username in self.usernames: if text == username: print("Username taken") def Focused_entry(self): print("Focused (Entered) the entry widget") def UnFocused_entry(self): print("UnFocused (Left) the entry widget")
In this section, we’ll explain each of the key bindings we used in the code above.
Note: The reason we use lambdas, is so that we can pass parameters into the function that gets called. The function that you pass into the second parameter of
bind() should not have any brackets. Hence the lambdas is a way to work around this limitation. (This issue arises because you need a function name in
bind(), not a function call.
print(value) is a call, while
self.master.bind('a', lambda event: print("A was pressed"))
The above code will print out “A was pressed” to the screen, if the “a” key is pressed. We can bind any key in this manner, such as “b”, “c”, “1” etc.
self.frame.bind('<Enter>', lambda event: print("Entered Frame"))
In the above code, we print out “Entered Frame”, if the mouse cursor moves over the frame. Try running the code to see it properly.
self.label.bind('<Button-1>', lambda event: print("Mouse clicked the label"))
The above code will cause Tkinter to print out a message, if we click on the label with the mouse.
self.button.bind('<Enter>',lambda event: self.color_change(self.button,"green")) self.button.bind('<Leave>',lambda event: self.color_change(self.button,"black"))
The above code creates the hover effect. If you “enter” the button with your cursor, then it will change color to green. If to leaves the button, it will change the color back to black.
self.entry.bind('<Key>', lambda event: self.pass_check()) self.entry.bind('<FocusIn>', lambda event: self.Focused_entry()) self.entry.bind('<FocusOut>', lambda event: self.UnFocused_entry())
This code has two purposes. The <Key> bind, keeps checking to see if the username already exists. Each time you enter a new key, it checks the entered username with the list of existing usernames by calling the
The other two bindings check to see if the entry widget is under focus or not. If you click on the Entry widget, the
Focused_entry() function will call. If you select some other widget like another entry, then it will become defocused and call the
List of Key Bindings
Here is a list of key bindings in Tkinter. Remember, you can attach these to any widget, not just the Tkinter window.
|<Button-1>||<Button-1> for the left mouse click, <Button-2> for the middle mouse (scroll wheel), <Button-3> for right mouse click.|
|<B1-Motion>||Used for holding down a mouse key while dragging it. <B1-Motion> for holding and dragging the left mouse button, and so on.|
|<ButtonRelease-1>||Used to detect when the mouse button is released.|
|<Double-Button-1>||Used for detecting mouse double clicking.|
|<Enter>||The Widget has been “entered”, such as the mouse cursor hovering over it.|
|<Leave>||The Widget has been “left”, such as the mouse cursor leaving it’s occupied area.|
|<FocusIn>||Widget has been “focused”, such as clicking on the widget (selecting it).|
|<FocusOut>||Widget has been “unfocused”, like deselecting it (and moving focus elsewhere)|
|<Return>||Key Binding for the Enter Key.|
|<Key>||This key binding activates if any Key is pressed. The Key that was pressed can be located in the event object in the |
|a||Used for regular keys. Just a simple “a” is all you need to bind it to the Key “a”.|
Another really interesting use of the Key binding feature, is in this video of ours. Here we made a Syntax highlighter using the Text Widget, which relies on Key bindings to actually call the function responsible for coloring the special keywords and commands.
This marks the end of the Tkinter Key Binding Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.