The Wayback Machine - https://web.archive.org/web/20240213184902/https://www.geeksforgeeks.org/how-to-pass-arguments-to-tkinter-button-command/
Open In App
Related Articles

How to Pass Arguments to Tkinter Button Command?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

When a user hits the button on the Tkinter Button widget, the command option is activated. In some situations, it’s necessary to supply parameters to the connected command function. In this case, the procedures for both approaches are identical; the only thing that has to vary is the order in which you use them.

Method 1: Pass Arguments to Tkinter Button using the lambda function

Import the Tkinter package and create a root window. Give the root window a title(using title()) and dimension(using geometry()), now Create a button using (Button()). Use mainloop() to call the endless loop of the window. lambda function creates a temporary simple function to be called when the Button is clicked.

Python3

# importing tkinter
import tkinter as tk
 
# defining function
 
 
def func(args):
    print(args)
 
 
# create root window
root = tk.Tk()
 
# root window title and dimension
root.title("Welcome to GeekForGeeks")
root.geometry("380x400")
 
# creating button
btn = tk.Button(root, text="Press", command=lambda: func("See this worked!"))
btn.pack()
 
# running the main loop
root.mainloop()

                    

Output:

Pass Arguments to Tkinter Button

using lambda

Method 2: Pass Arguments to Tkinter Button using partial 

Import the Tkinter package and create a root window. Give the root window a title(using title()) and dimension(using geometry()), now Create a button using (Button()). Use mainloop() to call the endless loop of the window. command=partial returns a callable object that behaves like a func when it is called.

Python3

# importing necessary libraries
from functools import partial
import tkinter as tk
 
# defining function
 
 
def function_name(func):
    print(func)
 
 
# creating root window
root = tk.Tk()
 
# root window title and dimension
root.title("Welcome to GeekForGeeks")
root.geometry("380x400")
 
# creating button
btn = tk.Button(root, text="Click Me", command=partial(
    function_name, "Thanks, Geeks for Geeks !!!"))
btn.pack()
 
# running the main loop
root.mainloop()

                    

Output:

Pass Arguments to Tkinter Button

using partial


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.


Last Updated : 03 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials