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.
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)
Explanation:
Labeldisplays text.Entryallows text input.Buttonexecutes 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.
Explanation:
grid(row, column)places widgets in a table-like structure.columnspan=2makes the button span two columns.
4. Message Box (Popup Dialogs)
Explanation:
messagebox.showinfo()creates a popup message.
5. File Dialog (Open/Save Files)
Explanation:
filedialog.askopenfilename()allows users to select a file.
6. Building a Simple Calculator
Explanation:
- Uses
grid()to place buttons in a calculator layout. eval()computes the mathematical expression entered by the user.lambdaallows passing values dynamically to functions.
7. Adding a Menu Bar
Explanation:
menu.add_command()adds menu items.menu_bar.add_cascade()adds dropdown menus.
Summary
| Feature | Code |
|---|---|
| Basic Window | tk.Tk() |
| Label | Label(root, text="Hello") |
| Button | Button(root, text="Click Me", command=function) |
| Entry (Text Box) | Entry(root) |
| Grid Layout | widget.grid(row=0, column=0) |
| Popup Message | messagebox.showinfo("Title", "Message") |
| File Dialog | filedialog.askopenfilename() |
| Calculator | eval(entry.get()) |
| Menu Bar | Menu(root) |
No comments:
Post a Comment