Certainly! Here's a refactored version of your Python 3.12 Tkinter code. The refactoring focuses on improving readability, reducing redundancy, and enhancing modularity by introducing helper methods for repetitive tasks such as frame creation and adding separators or clickable labels.
import tkinter as tk
from tkinter import ttk
class YourAppClass:
SIDEBAR_WIDTH = 200
STATIC_FRAME_WIDTH = 100
def create_sidebar(self):
"""Create the sidebar and its components."""
# Create the main sidebar frame
sidebar = self._create_frame(
parent=self.root,
width=self.SIDEBAR_WIDTH,
bg=self.SIDEBAR_COLOR,
side='left',
anchor='nw',
fill='y'
)
# Create an additional static frame next to the sidebar
self._create_frame(
parent=self.root,
width=self.STATIC_FRAME_WIDTH,
bg=self.BACKGROUND_COLOR,
side='left',
anchor='nw',
fill='y'
)
# Add components to the sidebar
self._add_normal_buttons(sidebar)
self._add_scrollable_canvas(sidebar)
self._add_delete_table_section(sidebar)
def _create_frame(self, parent, width, bg, side, anchor, fill, expand=False):
"""Helper method to create and pack a frame."""
frame = tk.Frame(parent, width=width, bg=bg, bd=0, relief='flat')
frame.pack(side=side, anchor=anchor, fill=fill, expand=expand)
return frame
def _add_normal_buttons(self, sidebar):
"""Add the normal buttons section to the sidebar."""
# Create a frame for normal buttons
normal_buttons_frame = self._create_frame(
parent=sidebar,
width=None,
bg=self.SIDEBAR_COLOR,
side='top',
anchor='nw',
fill='x'
)
# Add "Create New Table" clickable label
create_table_label = self._create_clickable_label(
parent=normal_buttons_frame,
text="Create New Table",
command=self.create_new_table
)
create_table_label.pack(fill='x', padx=0, pady=0)
self.add_custom_hover(create_table_label)
# Add a separator below the button
self._add_separator(normal_buttons_frame)
def _add_scrollable_canvas(self, sidebar):
"""Add a scrollable canvas to the sidebar."""
# Create a frame to hold the canvas and scrollbar
scrollbar_frame = self._create_frame(
parent=sidebar,
width=None,
bg=self.SIDEBAR_COLOR,
side='top',
anchor='nw',
fill='both',
expand=True
)
# Create the canvas
canvas = tk.Canvas(
scrollbar_frame,
bg=self.SIDEBAR_COLOR,
highlightthickness=0
)
canvas.pack(side="left", fill="both", expand=True)
# Create the scrollbar
scrollbar = ttk.Scrollbar(
scrollbar_frame,
orient="vertical",
command=canvas.yview
)
scrollbar.pack(side="right", fill="y")
# Configure the canvas to use the scrollbar
canvas.configure(yscrollcommand=scrollbar.set)
# Create a frame inside the canvas to hold table labels
self.table_labels_frame = tk.Frame(canvas, bg=self.SIDEBAR_COLOR)
canvas.create_window((0, 0), window=self.table_labels_frame, anchor="nw")
# Bind events to adjust the scrollbar visibility
self._bind_scrollbar_events(canvas, scrollbar, scrollbar_frame)
def _bind_scrollbar_events(self, canvas, scrollbar, scrollbar_frame):
"""Bind configuration events to manage scrollbar visibility."""
def configure_scrollbar(event=None):
canvas.update_idletasks()
canvas_height = scrollbar_frame.winfo_height()
content_height = self.table_labels_frame.winfo_reqheight()
if content_height > canvas_height and not scrollbar.winfo_viewport():
scrollbar.pack(side="right", fill="y")
elif content_height <= canvas_height:
scrollbar.pack_forget()
canvas.configure(scrollregion=canvas.bbox("all"))
self.table_labels_frame.bind("<Configure>", configure_scrollbar)
scrollbar_frame.bind("<Configure>", configure_scrollbar)
def _add_delete_table_section(self, sidebar):
"""Add the delete table section to the sidebar."""
# Add a separator
self._add_separator(sidebar)
# Add "Delete Selected Table" clickable label
delete_table_label = self._create_clickable_label(
parent=sidebar,
text="Delete Selected Table",
command=self.delete_table
)
delete_table_label.pack(fill='x', padx=0, pady=0, side='bottom')
self.add_custom_hover(delete_table_label)
def _add_separator(self, parent):
"""Helper method to add a horizontal separator."""
separator = ttk.Separator(parent, orient='horizontal')
separator.pack(fill='x', pady=0)
def _create_clickable_label(self, parent, text, command):
"""Helper method to create a clickable label."""
label = tk.Label(parent, text=text, bg=self.SIDEBAR_COLOR, cursor="hand2")
label.bind("<Button-1>", lambda e: command())
return label
# Placeholder methods for demonstration purposes
def create_new_table(self):
"""Method to handle creating a new table."""
pass
def delete_table(self):
"""Method to handle deleting a selected table."""
pass
def create_clickable_label(self, parent, text, command):
"""Method to create a clickable label."""
return self._create_clickable_label(parent, text, command)
def add_custom_hover(self, widget):
"""Method to add hover effects to a widget."""
widget.bind("<Enter>", lambda e: widget.config(bg="lightgray"))
widget.bind("<Leave>", lambda e: widget.config(bg=self.SIDEBAR_COLOR))
# Initialization and other methods would go here
Refactoring Highlights:
-
Helper Methods:
_create_frame: Centralizes frame creation and packing, reducing repetition.
_add_separator: Encapsulates the addition of separators.
_create_clickable_label: Simplifies the creation of clickable labels with bound commands.
-
Enhanced Scrollbar Handling:
_bind_scrollbar_events: Separates scrollbar configuration logic, enhancing clarity.
- Removed the
scrollbar_visible flag by leveraging widget states and packing methods.
-
Modular Component Addition:
- Each section of the sidebar (buttons, scrollable canvas, delete section) is handled by dedicated methods, making the code easier to navigate and maintain.
-
Consistency and Readability:
- Consistent naming conventions and method structures improve the overall readability.
- Docstrings provide clear explanations of each method's purpose.
-
Placeholder Methods:
create_new_table, delete_table, create_clickable_label, and add_custom_hover are included as placeholders. Ensure these are properly defined elsewhere in your codebase.
Benefits of This Refactoring:
- Maintainability: Easier to update individual components without affecting others.
- Readability: Clear structure and separation of concerns make the code easier to understand.
- Reusability: Helper methods can be reused for similar widgets or sections elsewhere in the application.
- Scalability: Simplifies adding new features or components to the sidebar in the future.
Feel free to adjust the helper methods or structure further based on the specific needs and conventions of your larger codebase.