Wednesday, 19 March 2025

Creating GUI Using Tkinter

5.2  Creating GUI Using Tkinter

Creating a GUI Using Tkinter in Python

Tkinter is the standard Python library for creating Graphical User Interfaces (GUIs). It provides widgets like buttons, labels, text boxes, and more to build interactive applications.


1. Basic Tkinter Window

A simple Tkinter window can be created with just a few lines of code.


import tkinter as tk # Create the main application window root = tk.Tk() # Set window title root.title("My First Tkinter App") # Set window size root.geometry("400x300") # Run the Tkinter event loop root.mainloop()

Explanation:

  • tk.Tk() initializes the main window.
  • title("My First Tkinter App") sets the window title.
  • geometry("400x300") sets the window size.
  • mainloop() starts the GUI event loop.

2. Adding Widgets (Labels, Buttons, Entry)


import tkinter as tk root = tk.Tk() root.title("Simple GUI") root.geometry("400x300") # Create a Label label = tk.Label(root, text="Hello, Tkinter!", font=("Arial", 16)) label.pack(pady=10) # Add some padding # Create an Entry Field entry = tk.Entry(root, width=30) entry.pack(pady=10) # Function to handle button click def on_button_click(): user_text = entry.get() # Get text from entry label.config(text=f"Hello, {user_text}!") # Update label # Create a Button button = tk.Button(root, text="Click Me", command=on_button_click) button.pack(pady=10) root.mainloop()

Explanation:

  • Label displays text.
  • Entry allows text input.
  • Button executes a function when clicked.
  • pack() is used to arrange widgets.

3. Using Grid Layout

Instead of pack(), you can use grid() for better layout control.


import tkinter as tk root = tk.Tk() root.title("Grid Layout Example") # Create widgets tk.Label(root, text="Name:").grid(row=0, column=0, padx=10, pady=10) name_entry = tk.Entry(root) name_entry.grid(row=0, column=1, padx=10, pady=10) tk.Label(root, text="Age:").grid(row=1, column=0, padx=10, pady=10) age_entry = tk.Entry(root) age_entry.grid(row=1, column=1, padx=10, pady=10) # Button to print input values def submit(): print(f"Name: {name_entry.get()}, Age: {age_entry.get()}") tk.Button(root, text="Submit", command=submit).grid(row=2, column=0, columnspan=2, pady=10) root.mainloop()

Explanation:

  • grid(row, column) places widgets in a table-like structure.
  • columnspan=2 makes the button span two columns.

4. Message Box (Popup Dialogs)


import tkinter as tk from tkinter import messagebox def show_message(): messagebox.showinfo("Greeting", "Hello, Tkinter!") root = tk.Tk() root.title("Message Box Example") tk.Button(root, text="Show Message", command=show_message).pack(pady=20) root.mainloop()

Explanation:

  • messagebox.showinfo() creates a popup message.

5. File Dialog (Open/Save Files)


import tkinter as tk from tkinter import filedialog def open_file(): file_path = filedialog.askopenfilename() if file_path: print("Selected File:", file_path) root = tk.Tk() root.title("File Dialog Example") tk.Button(root, text="Open File", command=open_file).pack(pady=20) root.mainloop()

Explanation:

  • filedialog.askopenfilename() allows users to select a file.

6. Building a Simple Calculator


import tkinter as tk root = tk.Tk() root.title("Simple Calculator") entry = tk.Entry(root, width=30, borderwidth=5) entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10) # Function to handle button clicks def button_click(number): entry.insert(tk.END, number) def clear(): entry.delete(0, tk.END) 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") # Button layout buttons = [ ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3), ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3), ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3), ('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3) ] for text, row, col in buttons: tk.Button(root, text=text, width=5, height=2, command=lambda t=text: button_click(t) if t != '=' else calculate()).grid(row=row, column=col) tk.Button(root, text="C", width=5, height=2, command=clear).grid(row=4, column=3) root.mainloop()

Explanation:

  • Uses grid() to place buttons in a calculator layout.
  • eval() computes the mathematical expression entered by the user.
  • lambda allows passing values dynamically to functions.

7. Adding a Menu Bar


import tkinter as tk def open_file(): print("Open file clicked") root = tk.Tk() root.title("Menu Bar Example") menu_bar = tk.Menu(root) # File menu file_menu = tk.Menu(menu_bar, tearoff=0) file_menu.add_command(label="Open", command=open_file) file_menu.add_command(label="Exit", command=root.quit) menu_bar.add_cascade(label="File", menu=file_menu) root.config(menu=menu_bar) root.mainloop()

Explanation:

  • menu.add_command() adds menu items.
  • menu_bar.add_cascade() adds dropdown menus.

Summary

FeatureCode
Basic Windowtk.Tk()
LabelLabel(root, text="Hello")
ButtonButton(root, text="Click Me", command=function)
Entry (Text Box)Entry(root)
Grid Layoutwidget.grid(row=0, column=0)
Popup Messagemessagebox.showinfo("Title", "Message")
File Dialogfiledialog.askopenfilename()
Calculatoreval(entry.get())
Menu BarMenu(root)

No comments:

Post a Comment

Desktop Virtualisation

Desktop Virtualization ( DV ) Desktop Virtualization ( DV ) is a technique that creates an illusion of a desktop provided to the user. It d...