Tkinter
Tkinter
Tkinter is Python's standard library for building graphical user interfaces (GUIs). It provides
tools to create windows, dialogs, buttons, menus, and other GUI elements.
1. Tkinter Introduction
What is Tkinter?
o A built-in Python library for GUI development.
o Based on the Tk GUI toolkit.
o Cross-platform: Works on Windows, macOS, and Linux.
Why use Tkinter?
o Easy to learn and use.
o No need to install; it comes pre-installed with Python.
o Provides a wide range of widgets like buttons, labels, textboxes, etc.
import tkinter as tk
3. Tk Widgets
Widgets are the building blocks of a GUI application in Tkinter. Below are some commonly
used widgets:
a) Label
def on_click():
print("Button clicked!")
c) Entry
entry = tk.Entry(root)
entry.pack()
d) Text
e) Frame
frame = tk.Frame(root)
frame.pack()
f) Menu
menu = tk.Menu(root)
root.config(menu=menu)
menu.add_command(label="File")
menu.add_command(label="Edit")
4. Tkinter Examples
import tkinter as tk
# Add a label
label = tk.Label(root, text="Hello, Tkinter!", font=("Arial", 16))
label.pack()
# Add a button
def greet():
label.config(text="Button Clicked!")
import tkinter as tk
def login():
username = entry_user.get()
password = entry_pass.get()
print(f"Username: {username}, Password: {password}")
# Main window
root = tk.Tk()
root.title("Login Form")
root.geometry("300x150")
# Widgets
tk.Label(root, text="Username:").grid(row=0, column=0)
entry_user = tk.Entry(root)
entry_user.grid(row=0, column=1)
Example 3: Calculator
import tkinter as tk
def calculate():
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(tk.END, str(result))
except:
entry.delete(0, tk.END)
entry.insert(tk.END, "Error")
# Main window
root = tk.Tk()
root.title("Calculator")
root.geometry("300x200")
# Input field
entry = tk.Entry(root, font=("Arial", 18))
entry.pack()
# Buttons
for char in "1234567890+-*/=":
btn = tk.Button(root, text=char, command=lambda c=char:
entry.insert(tk.END, c) if c != '=' else calculate())
btn.pack(side=tk.LEFT)
# Run app
root.mainloop()
1. PyCharm:
o Advanced features for professional developers.
o Built-in support for Tkinter.
o Free Community Edition available.
2. Visual Studio Code:
o Lightweight and extensible.
o Requires Python extension for advanced features.
3. IDLE:
o Comes pre-installed with Python.
o Basic and suitable for beginners.
4. Jupyter Notebook:
o Ideal for data visualization and interactive coding.