Python Tkinter section

The Button Command with Parameters

Post by Amina Delali, March 20th, 2023

Description

We already used a button widget in the previous posts. A widget when you click on, it will execute a function. The name of this function is set as the command property of that button.

The problem is, when you define the command property you specify only the name of the function. But sometimes you need to use a function with a parameter. To simulate this situation, we will define a function that will need the associated button as a parameter.

We have a button that when we click on, its background color will change. So, the function needs to:

  • Have the actual background color value to know which background color assign to the button.
  • Have access to the button in question to change its background color property.

So, our function changeColor will have as a parameter the button itself.

Now, to define the property command of the button (the function that will be called), we will use lambda that will be equal to the call of the changeColor function with our button as a parameter.

Below, you will find the entire code that describes how the button is added to the main window of the application, and how its associated function is defined. You will also see the execution of the code.



The Code

Copy Code

from tkinter import *
main_window=Tk()
main_window.title("The Button Command with Parameters")
main_window.geometry('200x200+200+200'
main_window.configure(bg="#8800FF")

def changeColor(myButton):
    color myButton["bg"]
    if color=="gold":
        myButton["bg"]="lightsalmon"
    else:
        myButton["bg"]="gold"


button1 Button(main_window,text="Change Color",
                bg="gold",
                command=lambdachangeColor(button1))
button1.pack(pady=20,padx=20,side=RIGHT,anchor=CENTER)


main_window.mainloop()

The Output





Something to say?

If you want to add something about this post, please feel free to do it by commenting below 🙂.