Tkinter is a python module for building a great GUI or desktop application. As a Data Science Learner, I always use it to prototype any product or project I want to develop. There are many widgets of the Tkinter module like labels, buttons, PhotoImage e.t.c that are very useful. In this entire tutorial, you will learn the implementation of the Tkinter Buttons with various examples.
Examples on Tkinter Button
Example 1: How to create a buttons in Tkinter
To create a button in Tkinter you have to use the Button() constructor. Inside the constructor, you have to pass the root interface and text for the button. Execute the below lines of code to create it.
from tkinter import *
from tkinter import ttk
root = Tk()
button = ttk.Button(root,text="Click Here!")
button.pack()
root.mainloop()
The statement button.pack() and mainloop() is use to display the GUI in Windows and Pycharm.
Output

Example 2: Add a Callback Definition to the button
The above example is to create a button only. It is not doing anything. To make a button to do something you have to add a callback function to it that will run when you click the button.
from tkinter import *
from tkinter import ttk
root = Tk()
button = ttk.Button(root,text="Click Here!")
def button_callback():
print("Button Clicked")
button.config(command=button_callback)
button.pack()
root.mainloop()
Here I am first creating a button_callback() function. Then I am using the definition name with the button.config() method. When you will run the code and click on the button you will get the following output.
Output

You can see the I have clicked on the button 4 times.
Example 3: Invoke Tkinter Buttons
You can also invoke the button anywhere you want in code. You have to just use the invoke() method. Using the same definition created in Example 2 for the button. If I use the below code then you will get the same output as the above Button Clicked.
button.invoke()
Example 4: How to enable or disable a button in Tkinter
You can also enable or disable a button in Tkinter. It can be done using the state() method.
Disable Tkinter Button
To disable the button you have to use the state([“disabled”]).
button.state(["disabled"])
Now you will not be able to click the button.
Output

Enable Button
After disabling, you again want to enable the button then use the state([“!disabled”]). It will enable the button.
button.state(["!disabled"])
Output

Conclusion
The Tkinter button is very useful for manipulating and calculation of your data if you want to do a project on Machine Learning or data science. These are the implementation of the basics of the button. I hope you have found it very useful. If you have any other query then you can contact us for more help.
Source:
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.