In this article, we’ll explore how to pass arguments to a Tkinter button, which allows us to pass any values or functions when a button is clicked. If you’re just beginning your journey with Tkinter, this guide will be especially useful. Before diving into the tutorial on passing arguments, we’ll start with a brief overview of what Tkinter is, followed by the steps to pass arguments to a Tkinter button
Tkinter Library in python:
Tkinter is a Python library used for developing graphical user interface (GUI) applications. It functions similarly to Java’s Abstract Window Toolkit (AWT), but Tkinter is considered more efficient for Python development. The library includes built-in tools like buttons, text fields, checkboxes, combo boxes, radio buttons, and more, making it easy to create interactive interfaces. If you’re interested in learning through hands-on projects, you can start by building a simple music player GUI app using Tkinter.
Passing Argument To Tkinter Button:
Next, we’ll learn how to pass arguments to a Tkinter button. There are two straightforward methods to do this:
- Using custom functions
- Using anonymous functions, like lambda functions
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.....!
In the code above, we start by importing the necessary modules, then create a window with dimensions of 500×500 for height and width. Finally, we add a button and use a lambda function to pass an argument. In this case, I’ve named the function red
, but you can replace it with any function of your choice.
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("400*400") #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’ve used custom functions instead of lambda functions. However, the drawback of custom functions is that you cannot directly pass arguments to a single function. To address this issue, we use nested functions. In the example, I’ve written a function called green
inside another function named blue
. This approach allows us to pass arguments effectively. You can, of course, use your own function names. I hope this article proves helpful to you!