Python GUI Programming with Tkinter
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications.
Importing the Module
import tkinter as tk
Creating a Basic Window
To create a GUI application, you start by creating the main window.
import tkinter as tk
root = tk.Tk()
root.title("My First GUI")
root.geometry("300x200")
root.mainloop()
Widgets
Widgets are the building blocks of a GUI application.
Label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()
Button
def on_click():
print("Button clicked!")
button = tk.Button(root, text="Click Me", command=on_click)
button.pack()
Entry
entry = tk.Entry(root)
entry.pack()
Layout Managers
Tkinter provides three main layout managers to arrange widgets: pack(), grid(), and place().
pack()
Organizes widgets in blocks before placing them in the parent widget.
label.pack(side=tk.TOP)
button.pack(side=tk.BOTTOM)
grid()
Organizes widgets in a table-like structure.
label.grid(row=0, column=0)
button.grid(row=1, column=1)
Event Handling
You can bind functions to events (like button clicks) using the command parameter or the bind() method.
def greet():
print("Hello!")
btn = tk.Button(root, text="Greet", command=greet)
btn.pack()