Buttons in Tkinter (GUI Programming) – Python Tkinter Tutorial
In our previous articles we learnt about our “first GUI application” and labels in python. In this article we will learn about Buttons in python.
Buttons: Buttons is a type of widget which is used to perform a specific operation when it is clicked. This widget is most used widget as compared to others.
Let’s have an example to understand it in a better way:-
Example 1:
#Button in python GUI from tkinter import * # creating root window root = Tk() root.title("Welcome to Python Lobby") # function defined which is called when button is clicked def clicked(): print("I am clicked") # placing Button to our GUI app btn = Button(root, text="Click me", command = clicked) btn.pack() root.geometry('250x200') root.mainloop() #
Output:
Explanation:
Step 1: We imported tkinter package using “import” keyword.
Step 2: We created an object “root” variable to call Tk() function, which is pre-defined in tkinter library responsible for executing code for creating a small GUI window.
Step 4: Next we have used same root object to customize the title of our GUI application by passing string value as an argument.
Step 5: After that in next line, we have defined the function clicked().
Step 6: After that we have created our Button by calling passing some required parameters ie. root , text and command.
root = main object of our application or root object.
text = text we want to display on our button.
command = action to take when button is clicked.
Note: We have called our function ie. clicked() when our button is called. Hence it displayed “I am clicked”.
Important: “btn.pack()” it is a type of geometry manager that we will discuss later in our upcoming articles.
Step 7: Call mainloop() function to finally execute our loop.