What is Python Tkinter
Python is an interpreted, high-level and general-purpose programming language. Tkinter is Python’s de facto standard GUI (Graphical User Interface) package. It is a cross-platform package, which means you build once and deploy everywhere.
Tkinter provides several GUI widgets like buttons, menus, canvas, text, frames, label, etc. It also provides an object-oriented interface to the Tk GUI toolkit.
Prerequisites
To start working with Tkinter, you need to import the Tkinter module.
import tkinter
Creating the Main Window
To create the main window of an application, you need to create an object of the Tk class.
# create the main window
window = tkinter.Tk()
You can set the title of the main window using the title() method.
# set the title
window.title("My Application")
You can also set the size of the window using the geometry() method.
# set the size
window.geometry("400x400")
Adding Widgets
You can add various widgets to the main window of the application.
# create a label
label = tkinter.Label(window, text="Hello World!")
# add the label to the window
label.pack()
You can also add buttons, text boxes and other widgets.
# create a button
button = tkinter.Button(window, text="Click Me!")
# add the button to the window
button.pack()
Event Handling
You can also handle various events such as button clicks, mouse movements, etc.
# handle the button click event
def on_click():
print("Button clicked!")
# bind the event handler
button.configure(command=on_click)
Running the Application
To start the application, you need to enter the main event loop.
# start the application
window.mainloop()
Conclusion
In this tutorial, you have learned how to use Python’s Tkinter library to create a simple GUI application. Tkinter provides an object-oriented interface to the Tk GUI toolkit. You can create various widgets, such as labels, buttons, text boxes, etc., and also handle various events, such as button clicks, mouse movements, etc.