mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+337
-290
@@ -1,292 +1,339 @@
|
||||
---
|
||||
description: This rule file outlines the best practices for developing GUI applications with tkinter in Python, including code organization, performance, security, testing, and tooling.
|
||||
globs: *.py
|
||||
description: Definitive guidelines for building modern, maintainable, and performant Tkinter applications using best practices, ttk, and ttkbootstrap.
|
||||
globs: **/*.py
|
||||
---
|
||||
# tkinter Best Practices: Optimizing Performance and Code Structure
|
||||
|
||||
This document outlines the best practices for developing GUI applications with `tkinter` in Python. It covers code organization, performance considerations, common pitfalls, security aspects, testing strategies, and recommended tooling.
|
||||
|
||||
## Library Information:
|
||||
|
||||
- Name: tkinter
|
||||
- Tags: ui, gui, python, desktop
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1. Directory Structure
|
||||
|
||||
A well-organized directory structure is crucial for maintainability and scalability. Here's a recommended structure:
|
||||
|
||||
|
||||
my_tkinter_app/
|
||||
├── app/
|
||||
│ ├── __init__.py
|
||||
│ ├── main_window.py # Main application window
|
||||
│ ├── widgets/
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── custom_button.py
|
||||
│ │ └── ...
|
||||
│ ├── models/
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── data_model.py
|
||||
│ │ └── ...
|
||||
│ ├── controllers/
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── main_controller.py
|
||||
│ │ └── ...
|
||||
│ ├── views/
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── main_view.py
|
||||
│ │ └── ...
|
||||
│ └── utils.py
|
||||
├── tests/
|
||||
│ ├── __init__.py
|
||||
│ ├── test_main_window.py
|
||||
│ ├── test_custom_button.py
|
||||
│ └── ...
|
||||
├── LICENSE
|
||||
├── README.md
|
||||
├── requirements.txt
|
||||
└── main.py # Entry point to run the application
|
||||
|
||||
|
||||
- `app/`: Contains the application's source code, including UI elements, logic, and data models.
|
||||
- `widgets/`: Holds custom widgets that extend `tkinter`'s built-in widgets.
|
||||
- `models/`: Defines data models and business logic.
|
||||
- `controllers/`: Manages interactions between the view and the model.
|
||||
- `views/`: Defines the user interface.
|
||||
- `tests/`: Contains unit tests and integration tests.
|
||||
- `LICENSE`: Project License
|
||||
- `README.md`: Project Documentation
|
||||
- `requirements.txt`: Lists project dependencies.
|
||||
- `main.py`: Application entry point.
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
- Use descriptive and consistent names for files and modules.
|
||||
- Follow the snake_case naming convention for Python files (e.g., `main_window.py`, `custom_button.py`).
|
||||
- For class names, use PascalCase (e.g., `MainWindow`, `CustomButton`).
|
||||
- For variable and function names, use snake_case (e.g., `window_width`, `calculate_area`).
|
||||
|
||||
### 1.3. Module Organization
|
||||
|
||||
- Break down large applications into smaller, manageable modules.
|
||||
- Each module should have a specific purpose and should be responsible for a single aspect of the application.
|
||||
- Use relative imports within the `app/` directory to maintain a clear hierarchy.
|
||||
python
|
||||
# Example: In app/controllers/main_controller.py
|
||||
from ..models import data_model
|
||||
|
||||
- Avoid circular dependencies between modules.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
- Adopt a component-based architecture to promote reusability and maintainability.
|
||||
- Encapsulate UI elements and their associated logic into custom widgets.
|
||||
- Consider using the Model-View-Controller (MVC) or Model-View-Presenter (MVP) design patterns.
|
||||
|
||||
### 1.5. Code Splitting
|
||||
|
||||
- Decompose complex functions and classes into smaller, more focused units.
|
||||
- Limit the size of individual files to improve readability and reduce cognitive load.
|
||||
- Use separate files for UI definitions, event handling logic, and data processing.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1. Design Patterns
|
||||
|
||||
- **MVC (Model-View-Controller):** Separates data (Model), UI (View), and user interaction logic (Controller).
|
||||
- **Observer:** Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Useful for updating the UI when the underlying data changes.
|
||||
- **Factory:** Used to create objects without specifying the exact class of object that will be created. Useful for creating widgets dynamically.
|
||||
|
||||
### 2.2. Recommended Approaches
|
||||
|
||||
- **Object-Oriented Programming (OOP):** Structure your Tkinter application using classes to improve code readability and maintainability. Encapsulate components within their classes for better modularity and separation of concerns.
|
||||
- **Consistent Layout Management:** Choose a consistent layout manager (`pack()`, `grid()`, or `place()`) for each container, and avoid mixing them within the same container to prevent layout issues.
|
||||
- **Threading for Long Tasks:** Use Python's threading capabilities for long-running tasks to keep the GUI responsive. Run background tasks without freezing the main application window.
|
||||
|
||||
### 2.3. Anti-Patterns and Code Smells
|
||||
|
||||
- **Global Variables:** Avoid global variables; use instance variables instead to minimize conflicts and enhance code clarity.
|
||||
- **Mixing Layout Managers:** Don't mix `pack()`, `grid()`, and `place()` within the same container, as it can lead to unpredictable layout behavior.
|
||||
- **Blocking the Main Thread:** Avoid performing long-running operations directly in the main thread, as this can freeze the GUI.
|
||||
- **Deeply Nested Code:** Avoid deeply nested code blocks, as they can reduce readability. Break down complex logic into smaller functions.
|
||||
- **Magic Numbers/Strings:** Replace numeric literals and string constants with named constants to improve readability and maintainability.
|
||||
|
||||
### 2.4. State Management
|
||||
|
||||
- Use `StringVar`, `IntVar`, `BooleanVar`, and `DoubleVar` classes to manage widget state and automatically update UI elements.
|
||||
- Create dedicated model classes to hold application data.
|
||||
- Use observable patterns to notify UI elements of data changes.
|
||||
|
||||
### 2.5. Error Handling
|
||||
|
||||
- Implement comprehensive error handling using `try...except` blocks.
|
||||
- Log errors to a file or console for debugging purposes.
|
||||
- Display user-friendly error messages in dialog boxes or status bars.
|
||||
- Implement global exception handling to prevent unhandled exceptions from crashing the application.
|
||||
- Use `tkinter.messagebox` for displaying warning, info and error messages.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
- **Minimize Redrawing:** Use `update_idletasks()` to reduce unnecessary redraws of the UI, enhancing responsiveness during updates.
|
||||
- **Efficient Widget Configuration:** Avoid unnecessary widget configuration changes, as they can trigger redraws.
|
||||
- **Caching:** Cache frequently accessed data to reduce database or network I/O.
|
||||
- **Debouncing:** Implement debouncing for event handlers that trigger computationally expensive operations.
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
- Avoid creating unnecessary widget instances.
|
||||
- Destroy widgets when they are no longer needed using `.destroy()`.
|
||||
- Limit the use of images and large data structures to reduce memory footprint.
|
||||
- Use weak references to avoid circular dependencies and memory leaks.
|
||||
|
||||
### 3.3. Rendering Optimization
|
||||
|
||||
- Use the `Canvas` widget for drawing complex graphics instead of creating many individual widgets.
|
||||
- Optimize drawing operations by minimizing the number of draw calls.
|
||||
- Use double buffering to prevent flickering during updates.
|
||||
|
||||
### 3.4 Lazy Loading
|
||||
|
||||
- Load only the necessary data and UI elements when the application starts.
|
||||
- Delay loading less frequently used features until they are requested by the user.
|
||||
- Use placeholder widgets or progress indicators while data is being loaded.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1. Common Vulnerabilities
|
||||
|
||||
- **Command Injection:** Avoid executing shell commands directly from the application, as this can lead to command injection vulnerabilities.
|
||||
- **Cross-Site Scripting (XSS):** Be cautious when displaying user-provided data in UI elements, as this can lead to XSS vulnerabilities.
|
||||
- **Path Traversal:** Sanitize file paths to prevent path traversal vulnerabilities.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
- Validate all user inputs to prevent malicious data from entering the application.
|
||||
- Use regular expressions or custom validation functions to ensure that inputs conform to expected formats.
|
||||
- Sanitize inputs by escaping special characters and removing potentially harmful content.
|
||||
- Implement rate limiting to prevent denial-of-service attacks.
|
||||
|
||||
### 4.3. Authentication and Authorization
|
||||
|
||||
- Use secure authentication protocols, such as OAuth 2.0 or OpenID Connect.
|
||||
- Store user credentials securely using password hashing algorithms like bcrypt or Argon2.
|
||||
- Implement role-based access control to restrict access to sensitive data and functionality.
|
||||
|
||||
### 4.4. Data Protection
|
||||
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure communication protocols, such as HTTPS, to protect data during transmission.
|
||||
- Implement data masking or redaction to prevent exposure of sensitive information.
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
|
||||
- Use secure API endpoints with HTTPS.
|
||||
- Validate API responses to prevent data injection.
|
||||
- Use API keys or authentication tokens to control access to API resources.
|
||||
- Implement rate limiting to prevent API abuse.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1. Unit Testing
|
||||
|
||||
- Write unit tests for individual widgets, models, and controllers.
|
||||
- Use a testing framework, such as `unittest` or `pytest`, to automate the testing process.
|
||||
- Mock external dependencies, such as databases or network connections, to isolate the code being tested.
|
||||
- Test different scenarios, including normal conditions, edge cases, and error conditions.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
- Test the interaction between different components of the application.
|
||||
- Verify that data flows correctly between widgets, models, and controllers.
|
||||
- Test the application with different data sets to ensure that it handles various scenarios.
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
|
||||
- Simulate user interactions to test the application from start to finish.
|
||||
- Use a GUI testing tool, such as `selenium` or `pywinauto`, to automate the testing process.
|
||||
- Verify that the application behaves as expected in different environments.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
- Create a separate directory for test files (`tests/`).
|
||||
- Organize tests into modules that correspond to the application's module structure.
|
||||
- Use descriptive names for test functions to indicate what they are testing.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
- Use mocking to replace external dependencies with mock objects that simulate their behavior.
|
||||
- Use stubs to replace complex functions with simple implementations that return predefined values.
|
||||
- Mock GUI elements for testing the underlying logic.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1. Frequent Mistakes
|
||||
|
||||
- **Forgetting `mainloop()`:** The GUI will not display without calling `root.mainloop()` at the end of the script.
|
||||
- **Incorrect Event Handling:** Incorrectly binding events (e.g., binding to the wrong widget or using the wrong event type).
|
||||
- **Not Using Classes:** Failing to use classes for structuring the application, leading to disorganized and hard-to-maintain code.
|
||||
- **Confusing `StringVar` and Text:** Trying to get the value directly from the widget instead of using `StringVar.get()` for Entry or using `Text.get()` with appropriate indices.
|
||||
- **Improper Use of Layout Managers:** Mixing layout managers within the same container or failing to understand how they behave.
|
||||
|
||||
### 6.2. Edge Cases
|
||||
|
||||
- **Window Resizing:** Handling window resizing correctly to ensure that widgets are displayed properly.
|
||||
- **Different Screen Resolutions:** Testing the application on different screen resolutions to ensure that it looks good on all devices.
|
||||
- **Unicode Support:** Handling Unicode characters correctly to support different languages.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
- There are significant differences between Python 2.x and Python 3.x regarding the `tkinter` module name (Tkinter vs. tkinter). Remember to use `import tkinter as tk` for Python 3 and `import Tkinter as tk` for Python 2.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
- Ensure compatibility between tkinter and other technologies used in the application (e.g., databases, web frameworks).
|
||||
- Test the application on different operating systems to ensure that it behaves consistently.
|
||||
|
||||
### 6.5. Debugging
|
||||
|
||||
- Use the Python debugger (`pdb`) to step through the code and inspect variables.
|
||||
- Add logging statements to track the flow of execution and identify errors.
|
||||
- Use GUI debugging tools to inspect widget properties and layouts.
|
||||
- Learn to read the often cryptic traceback messages from tkinter errors. They often provide valuable clues.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Tools
|
||||
|
||||
- **IDE:** VS Code, PyCharm, Spyder
|
||||
- **GUI Designer:** Tkinter Designer (third party, code generation), PAGE (drag-and-drop)
|
||||
- **Testing Framework:** `unittest`, `pytest`
|
||||
- **Linting:** `flake8`, `pylint`
|
||||
- **Formatting:** `black`, `autopep8`
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
- Use `pip` and `virtualenv` to manage dependencies and create isolated environments.
|
||||
- Create a `requirements.txt` file to list all dependencies.
|
||||
- Use a build tool, such as `setuptools` or `cx_Freeze`, to create distributable packages.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
- Use a linter to enforce coding style and identify potential errors.
|
||||
- Use a formatter to automatically format the code according to PEP 8 guidelines.
|
||||
- Configure the IDE to run the linter and formatter automatically when saving files.
|
||||
|
||||
### 7.4. Deployment
|
||||
|
||||
- Use a deployment tool, such as `pyinstaller` or `cx_Freeze`, to create standalone executables.
|
||||
- Package the application with all necessary dependencies.
|
||||
- Provide installation instructions for different operating systems.
|
||||
- For web-based tkinter applications (using something like eel), follow appropriate web deployment strategies.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
- Use a CI/CD tool, such as Jenkins, GitLab CI, or GitHub Actions, to automate the build, test, and deployment processes.
|
||||
- Configure the CI/CD pipeline to run unit tests, integration tests, and end-to-end tests automatically.
|
||||
- Use code coverage tools to measure the effectiveness of the tests.
|
||||
|
||||
By adhering to these best practices, you can create robust, maintainable, and performant tkinter applications.
|
||||
# tkinter Best Practices
|
||||
|
||||
Tkinter is Python's standard GUI toolkit. To build modern, maintainable, and responsive applications in 2025, adhere to these opinionated best practices.
|
||||
|
||||
## 1. Modern Theming: `ttk` and `ttkbootstrap`
|
||||
|
||||
Always use `tkinter.ttk` widgets for a native look and feel. For a truly modern aesthetic, integrate `ttkbootstrap`.
|
||||
|
||||
* **Default to `ttk`**: `ttk` widgets automatically adopt the OS theme.
|
||||
* **Embrace `ttkbootstrap`**: For a flat, dark-mode-ready, and consistent cross-platform design, `ttkbootstrap` is the go-to. It's a drop-in replacement for `ttk` with enhanced styling.
|
||||
|
||||
❌ BAD: Using classic `tk` widgets
|
||||
```python
|
||||
import tkinter as tk
|
||||
root = tk.Tk()
|
||||
tk.Button(root, text="Old Button").pack()
|
||||
```
|
||||
|
||||
✅ GOOD: Using `ttk` widgets
|
||||
```python
|
||||
import tkinter as tk
|
||||
from tkinter import ttk # Always import ttk
|
||||
root = tk.Tk()
|
||||
ttk.Button(root, text="Themed Button").pack()
|
||||
```
|
||||
|
||||
✅ BEST: Using `ttkbootstrap` for modern themes
|
||||
```python
|
||||
import ttkbootstrap as ttk # Import ttkbootstrap as ttk
|
||||
from ttkbootstrap.constants import * # For constants like PRIMARY, INFO
|
||||
|
||||
root = ttk.Window(themename="superhero") # Apply a modern theme
|
||||
ttk.Button(root, text="Bootstrap Button", bootstyle="primary").pack(pady=10)
|
||||
```
|
||||
|
||||
## 2. Code Organization: Class-Based Views
|
||||
|
||||
Structure your application with clear separation of concerns. Use classes for each logical view or component to encapsulate widgets and their logic.
|
||||
|
||||
* **Main Application Class**: Manages the root window and switches between views.
|
||||
* **View Classes**: Each class represents a distinct part of the UI (e.g., `LoginView`, `DashboardView`).
|
||||
* **Thin Bootstrap**: A minimal `main.py` to launch the app.
|
||||
|
||||
❌ BAD: Monolithic script
|
||||
```python
|
||||
import tkinter as tk
|
||||
# ... hundreds of lines of mixed UI and logic ...
|
||||
def create_ui():
|
||||
root = tk.Tk()
|
||||
# ...
|
||||
root.mainloop()
|
||||
create_ui()
|
||||
```
|
||||
|
||||
✅ GOOD: Class-based structure
|
||||
```python
|
||||
import ttkbootstrap as ttk
|
||||
from typing import Type
|
||||
|
||||
class BaseView(ttk.Frame):
|
||||
def __init__(self, master: ttk.Window, controller: 'AppController') -> None:
|
||||
super().__init__(master)
|
||||
self.controller = controller
|
||||
|
||||
class MainView(BaseView):
|
||||
def __init__(self, master: ttk.Window, controller: 'AppController') -> None:
|
||||
super().__init__(master, controller)
|
||||
ttk.Label(self, text="Welcome to the App!").pack(pady=20)
|
||||
ttk.Button(self, text="Go to Settings", command=self.controller.show_settings).pack()
|
||||
|
||||
class SettingsView(BaseView):
|
||||
def __init__(self, master: ttk.Window, controller: 'AppController') -> None:
|
||||
super().__init__(master, controller)
|
||||
ttk.Label(self, text="Settings Page").pack(pady=20)
|
||||
ttk.Button(self, text="Back to Main", command=self.controller.show_main).pack()
|
||||
|
||||
class AppController:
|
||||
def __init__(self, root: ttk.Window) -> None:
|
||||
self.root = root
|
||||
self.current_view: BaseView | None = None
|
||||
self._views: dict[str, Type[BaseView]] = {
|
||||
"main": MainView,
|
||||
"settings": SettingsView
|
||||
}
|
||||
self.show_main()
|
||||
|
||||
def _switch_view(self, view_name: str) -> None:
|
||||
if self.current_view:
|
||||
self.current_view.destroy()
|
||||
ViewClass = self._views[view_name]
|
||||
self.current_view = ViewClass(self.root, self)
|
||||
self.current_view.pack(fill=ttk.BOTH, expand=True)
|
||||
|
||||
def show_main(self) -> None:
|
||||
self._switch_view("main")
|
||||
|
||||
def show_settings(self) -> None:
|
||||
self._switch_view("settings")
|
||||
|
||||
if __name__ == "__main__":
|
||||
root = ttk.Window(themename="flatly")
|
||||
root.title("My Modern Tkinter App")
|
||||
root.geometry("400x300")
|
||||
app = AppController(root)
|
||||
root.mainloop()
|
||||
```
|
||||
|
||||
## 3. Geometry Managers: `grid` is King, `pack` for Simplicity
|
||||
|
||||
Choose one geometry manager per parent container and stick to it. `grid` offers the most control and is generally preferred for complex layouts. Use `pack` only for very simple, linear arrangements.
|
||||
|
||||
* **Never mix `pack()` and `grid()` in the same parent widget.** This is a common source of layout bugs.
|
||||
* **Separate widget creation from layout calls.** Chaining `widget.pack()` returns `None`, making the widget unusable later.
|
||||
|
||||
❌ BAD: Mixing `pack` and `grid` in the same frame
|
||||
```python
|
||||
import tkinter as tk
|
||||
root = tk.Tk()
|
||||
frame = tk.Frame(root)
|
||||
frame.pack()
|
||||
tk.Label(frame, text="Label 1").pack()
|
||||
tk.Button(frame, text="Button 1").grid(row=0, column=1) # ❌ Will cause TclError
|
||||
```
|
||||
|
||||
❌ BAD: Chaining geometry manager calls
|
||||
```python
|
||||
import tkinter as tk
|
||||
root = tk.Tk()
|
||||
my_button = tk.Button(root, text="Click Me").pack() # my_button is now None
|
||||
# my_button.config(text="New Text") # ❌ AttributeError: 'NoneType' object has no attribute 'config'
|
||||
```
|
||||
|
||||
✅ GOOD: Using `grid` consistently
|
||||
```python
|
||||
import ttkbootstrap as ttk
|
||||
root = ttk.Window()
|
||||
root.title("Grid Layout")
|
||||
|
||||
# Configure grid to expand with window
|
||||
root.columnconfigure(0, weight=1)
|
||||
root.rowconfigure(0, weight=1)
|
||||
|
||||
main_frame = ttk.Frame(root)
|
||||
main_frame.grid(row=0, column=0, sticky="nsew", padx=10, pady=10)
|
||||
|
||||
# Configure frame's grid
|
||||
main_frame.columnconfigure(1, weight=1) # Make column 1 expandable
|
||||
|
||||
ttk.Label(main_frame, text="Username:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
|
||||
username_entry = ttk.Entry(main_frame)
|
||||
username_entry.grid(row=0, column=1, sticky="ew", padx=5, pady=5)
|
||||
|
||||
ttk.Label(main_frame, text="Password:").grid(row=1, column=0, sticky="w", padx=5, pady=5)
|
||||
password_entry = ttk.Entry(main_frame, show="*")
|
||||
password_entry.grid(row=1, column=1, sticky="ew", padx=5, pady=5)
|
||||
|
||||
ttk.Button(main_frame, text="Login").grid(row=2, column=0, columnspan=2, pady=10)
|
||||
```
|
||||
|
||||
## 4. Data Binding: Use Tkinter Variables
|
||||
|
||||
For dynamic UI elements (labels, entries, checkboxes), use `StringVar`, `IntVar`, `BooleanVar`, or `DoubleVar`. These variables notify linked widgets of changes automatically.
|
||||
|
||||
❌ BAD: Updating labels with regular Python variables
|
||||
```python
|
||||
import tkinter as tk
|
||||
count = 0
|
||||
def increment():
|
||||
global count
|
||||
count += 1
|
||||
label.config(text=f"Count: {count}") # Manual update
|
||||
root = tk.Tk()
|
||||
label = tk.Label(root, text=f"Count: {count}")
|
||||
label.pack()
|
||||
tk.Button(root, text="Increment", command=increment).pack()
|
||||
```
|
||||
|
||||
✅ GOOD: Using `tk.IntVar`
|
||||
```python
|
||||
import tkinter as tk
|
||||
root = tk.Tk()
|
||||
count_var = tk.IntVar(value=0) # Initialize with a Tkinter variable
|
||||
def increment():
|
||||
count_var.set(count_var.get() + 1) # Update the Tkinter variable
|
||||
label = tk.Label(root, textvariable=count_var) # Link label to variable
|
||||
label.pack()
|
||||
tk.Button(root, text="Increment", command=increment).pack()
|
||||
```
|
||||
|
||||
## 5. Responsiveness: Avoid Blocking the Event Loop
|
||||
|
||||
Never use `time.sleep()` in a GUI application's main thread. It will freeze the entire UI. For delayed actions, use `root.after()`. For long-running tasks, use threading or `asyncio`.
|
||||
|
||||
❌ BAD: Freezing the UI with `time.sleep()`
|
||||
```python
|
||||
import tkinter as tk
|
||||
import time
|
||||
root = tk.Tk()
|
||||
status_label = tk.Label(root, text="Ready")
|
||||
status_label.pack()
|
||||
def long_task():
|
||||
status_label.config(text="Working...")
|
||||
root.update_idletasks() # Force update, but still blocks
|
||||
time.sleep(3) # ❌ GUI FREEZES for 3 seconds
|
||||
status_label.config(text="Done!")
|
||||
tk.Button(root, text="Start Task", command=long_task).pack()
|
||||
```
|
||||
|
||||
✅ GOOD: Non-blocking delays with `root.after()`
|
||||
```python
|
||||
import tkinter as tk
|
||||
root = tk.Tk()
|
||||
status_label = tk.Label(root, text="Ready")
|
||||
status_label.pack()
|
||||
def finish_task():
|
||||
status_label.config(text="Done!")
|
||||
def start_task():
|
||||
status_label.config(text="Working...")
|
||||
root.after(3000, finish_task) # Schedule finish_task after 3000ms (3 seconds)
|
||||
tk.Button(root, text="Start Task", command=start_task).pack()
|
||||
```
|
||||
|
||||
## 6. Image Handling: Keep References
|
||||
|
||||
Tkinter does not store references to `PhotoImage` objects internally. If your Python variable holding the `PhotoImage` goes out of scope, the image will disappear from the widget.
|
||||
|
||||
❌ BAD: Image disappears due to garbage collection
|
||||
```python
|
||||
import tkinter as tk
|
||||
from PIL import Image, ImageTk # Requires Pillow: pip install Pillow
|
||||
root = tk.Tk()
|
||||
def create_image_label():
|
||||
img = Image.open("icon.png") # Assume icon.png exists
|
||||
photo = ImageTk.PhotoImage(img)
|
||||
label = tk.Label(root, image=photo) # photo might be garbage collected
|
||||
label.pack()
|
||||
create_image_label()
|
||||
```
|
||||
|
||||
✅ GOOD: Explicitly keep a reference to the image
|
||||
```python
|
||||
import tkinter as tk
|
||||
from PIL import Image, ImageTk
|
||||
root = tk.Tk()
|
||||
img = Image.open("icon.png") # Assume icon.png exists
|
||||
photo = ImageTk.PhotoImage(img)
|
||||
label = tk.Label(root, image=photo)
|
||||
label.image = photo # ✅ Keep a reference directly on the widget
|
||||
label.pack()
|
||||
```
|
||||
|
||||
## 7. Essential Boilerplate: `root.mainloop()`
|
||||
|
||||
Always call `root.mainloop()` as the very last statement in your main application script. Without it, your GUI window will flash and immediately close.
|
||||
|
||||
❌ BAD: Window flashes and disappears
|
||||
```python
|
||||
import tkinter as tk
|
||||
root = tk.Tk()
|
||||
root.title("My App")
|
||||
tk.Label(root, text="Hello!").pack()
|
||||
# Forgot root.mainloop()
|
||||
```
|
||||
|
||||
✅ GOOD: Proper application lifecycle
|
||||
```python
|
||||
import tkinter as tk
|
||||
root = tk.Tk()
|
||||
root.title("My App")
|
||||
tk.Label(root, text="Hello!").pack()
|
||||
root.mainloop() # ✅ This is non-negotiable
|
||||
```
|
||||
|
||||
## 8. Robust Callbacks: Handle Exceptions
|
||||
|
||||
Wrap potentially failing operations in callbacks with `try...except` blocks. Tkinter often swallows exceptions in event handlers, making debugging difficult. Use `messagebox` to provide user feedback.
|
||||
|
||||
❌ BAD: Silent crashes in callbacks
|
||||
```python
|
||||
import tkinter as tk
|
||||
def risky_action():
|
||||
# This will raise FileNotFoundError if 'nonexistent.txt' doesn't exist
|
||||
with open("nonexistent.txt", "r") as f:
|
||||
content = f.read()
|
||||
print(content) # This line might never be reached
|
||||
root = tk.Tk()
|
||||
tk.Button(root, text="Do Risky Action", command=risky_action).pack()
|
||||
```
|
||||
|
||||
✅ GOOD: Graceful error handling
|
||||
```python
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox
|
||||
def risky_action_safe():
|
||||
try:
|
||||
with open("nonexistent.txt", "r") as f:
|
||||
content = f.read()
|
||||
messagebox.showinfo("Success", "File read successfully!")
|
||||
except FileNotFoundError:
|
||||
messagebox.showerror("Error", "The file 'nonexistent.txt' was not found.")
|
||||
except Exception as e:
|
||||
messagebox.showerror("Error", f"An unexpected error occurred: {e}")
|
||||
root = tk.Tk()
|
||||
tk.Button(root, text="Do Risky Action Safely", command=risky_action_safe).pack()
|
||||
```
|
||||
|
||||
## 9. Type Hints
|
||||
|
||||
Use type hints consistently for improved readability, maintainability, and static analysis. This is standard modern Python practice.
|
||||
|
||||
❌ BAD: Untyped functions and methods
|
||||
```python
|
||||
class MyWidget(tk.Frame):
|
||||
def __init__(self, master, data):
|
||||
super().__init__(master)
|
||||
self.data = data
|
||||
def update_label(self, new_text):
|
||||
# ...
|
||||
```
|
||||
|
||||
✅ GOOD: Typed functions and methods
|
||||
```python
|
||||
import tkinter as tk
|
||||
from typing import Any
|
||||
|
||||
class MyWidget(tk.Frame):
|
||||
def __init__(self, master: tk.Tk | tk.Frame, data: dict[str, Any]) -> None:
|
||||
super().__init__(master)
|
||||
self.data = data
|
||||
self.label = tk.Label(self, text=self.data.get("name", ""))
|
||||
self.label.pack()
|
||||
|
||||
def update_label(self, new_text: str) -> None:
|
||||
self.label.config(text=new_text)
|
||||
```
|
||||
Reference in New Issue
Block a user