Passing Argument To Tkinter Button

In this Article we are going to learn about how to Pass Argument To Tkinter Button. This will help us to pass any argument or function. This article will really be helpful to you if you are about to start your journey with tkinter. But before starting with this tutorial we will first learn about Tkinter and then we will learn about Passing Argument To Tkinter Button.

Tkinter Library in python:

Tkinter is a python library that is used to develop GUI (graphical user interface) apps. It is similar to the abstract window toolkit which is available in java, But however tkinter in python is more efficient than awt in java. This tkinter library consists of  inbuilt tools such as buttons, text, checkbox, combo box, radio button, etc. If you want to learn some projects of tkinter, Click this: A simple music player GUI app using Tkinter

Passing Argument To Tkinter Button:

Now we will be learn passing argument to tkinter button. There are two easy ways to pass arguments:

  • By using custom functions
  • By using anonymous functions such as lambda function

passing arguments with lambda function:

import tkinter as tk # importing modules
window=tk.Tk() 
window.geometry("500x500") # setting window size
def red(m):    #function definition
    print(m)
m="hello you clicked me .....!"    
button=tk.Button(window,text="HAY! Click ME",command=lambda: red(m)) # passing arguments
button.pack()
window.mainloop()

Output:

hello you clicked me .....!

here first you will get a window in which there will be a button.
when you click it you can see this : hello you clicked me .....!

From the above code we first import modules, Then create a window with size (500×500) height and width. Finally we create a button and pass a lambda function in it. I have written the function name as red. You can write your own.

passing arguments with custom function:

This method is somewhat complicated than the previous method, but even this method will also be useful to know.

  Code:

import tkinter as tk # importing modules
def blue(m):      # writing a nested functions
    def green():
        print(m.get())
    return green    

window=tk.Tk()   # creating a window
window.geometry("400x400") # setting window size
m=tk.StringVar(value="Hi Hello") 
button=tk.Button(window,text="Click Me",command=blue(m))
button.pack()
window.mainloop()

Output:

Hi Hello

In this code we have used custom functions rather than lambda function. But there is a problem with custom functions and that is :” you cannot use a single function”. So to solve this problem we are using nested functions. Here i have written a function named “green” in the function named “blue”. This is the only way to solve the problem. And do not forget that you can write function names of your own. Hope you find this article helpful.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top