Call a Function with a Button or a Key in Tkinter

In Tkinter applications, you can call functions when buttons are clicked or keys are pressed. This is achieved using the command parameter for buttons and the bind() method for key events.

Calling a Function with Button Click

The simplest way to call a function is by using the command parameter when creating a button ?

# Import the required libraries
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

# Create an instance of Tkinter Frame
win = Tk()

# Set the geometry of Tkinter Frame
win.geometry("700x350")

# Define a function for opening the Dialog box
def open_prompt():
    messagebox.showinfo("Message", "Click Okay to Proceed")

# Create a Label widget
Label(win, text="Click to Open the MessageBox").pack(pady=15)

# Create a Button for opening a dialog Box
ttk.Button(win, text="Open", command=open_prompt).pack()

win.mainloop()

Calling a Function with Key Press

You can bind keyboard keys to functions using the bind() method. The function must accept an event parameter ?

from tkinter import *
from tkinter import messagebox

# Create an instance of Tkinter Frame
win = Tk()
win.geometry("700x350")

# Define a function that accepts event parameter
def key_pressed(event):
    messagebox.showinfo("Key Pressed", f"You pressed: {event.keysym}")

# Create a Label widget
Label(win, text="Press 'Enter' or 'Space' key").pack(pady=15)

# Bind keys to the function
win.bind("<Return>", key_pressed)  # Enter key
win.bind("<space>", key_pressed)   # Space key

# Make sure the window can receive focus
win.focus_set()

win.mainloop()

Combining Button and Key Events

You can create applications that respond to both button clicks and key presses for the same function ?

from tkinter import *
from tkinter import ttk
from tkinter import messagebox

win = Tk()
win.geometry("700x350")

def show_message(event=None):
    messagebox.showinfo("Action", "Function called!")

# Create widgets
Label(win, text="Click button OR press 'Enter' key").pack(pady=15)
ttk.Button(win, text="Click Me", command=show_message).pack(pady=10)

# Bind Enter key to the same function
win.bind("<Return>", show_message)
win.focus_set()

win.mainloop()

Common Key Bindings

Key Binding Syntax Description
Enter <Return> Enter/Return key
Space <space> Spacebar
Escape <Escape> Escape key
F1 <F1> Function key F1
Ctrl+A <Control-a> Ctrl key + A

Conclusion

Use the command parameter for button clicks and bind() method for key events. Functions bound to keys must accept an event parameter, while button commands don't require it.

Updated on: 2026-03-25T20:48:29+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements