How to pass arguments to a Button command in Tkinter?



Let us assume that we are working with a tkinter application such that there are some buttons which need to pull out some window or event. In order to make the button fully functional, we can pass some arguments as the command value.

The Command is a Button attribute which takes the function name as the value. The function defines the working of a particular event.

Let us first create a button and add some events by passing arguments to its command attribute.

Example

In this example, we will create a window and a button that will close the window instantly.

#Importing the required library
from tkinter import *

#Create an instance of tkinter frame or window
win= Tk()

#Set the title
win.title("Button Command Example")

#Set the geometry
win.geometry("600x300")

#Create a label for the window
Label(win, text= "Example", font= ('Times New Roman bold',
20)).pack(pady=20)

#Defining a function
def close_event():
   win.destroy()

#Create a button and pass arguments in command as a function name
my_button= Button(win, text= "Close", font=('Helvetica bold', 20),
borderwidth=2, command= close_event)
my_button.pack(pady=20)

win.mainloop()

Output

By running the above code, we can pass the function as the argument to a Button command.

Click the "Close" button and it will close the window.


Advertisements