modify the buttons (plus and minus) so that are vertical to each other in a line (currently there are vertical) minus button left and + button right. Move the buttons to the top of the sidebar. Python 3.12 code: import sys
import sqlite3
from pathlib import Path
import tkinter as tk
from tkinter import ttk, messagebox, font
MEDIA_DB = Path(file).parent / 'media.db'
if sys.platform.startswith('win'):
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print("Error setting DPI awareness:", e)
def run_query(query: str, parameters: tuple = ()) -> list:
"""Execute a SQL query and return the results if it's a SELECT statement."""
with sqlite3.connect(MEDIA_DB) as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
if query.strip().lower().startswith("select"):
return result.fetchall()
conn.commit()
def create_tables() -> None:
"""Create the movies and series tables in the database if they do not exist."""
run_query('''
CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
movie TEXT,
year TEXT,
present BOOLEAN,
watched BOOLEAN,
notes TEXT
);
''')
run_query('''
CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
series TEXT,
seasons TEXT,
year TEXT,
present BOOLEAN,
seasons_present TEXT,
complete BOOLEAN,
watched BOOLEAN,
seasons_seen TEXT,
notes TEXT
);
''')
class MediaTracker(tk.Tk):
"""A Tkinter application to track movies and series."""
def _configure_grid(self) -> None:
"""Configure the grid layout for the main window."""
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(2, weight=1)
def _create_widgets(self) -> None:
"""Create and layout all the widgets in the application."""
self.header_canvas = tk.Canvas(self, bg='white', highlightthickness=0, height=100)
self.header_canvas.grid(row=0, column=1, columnspan=3, sticky='ew')
self.header_canvas.grid_propagate(False)
self.update_header("Movies")
def _create_sidebar_labels(self) -> None:
"""Create labels for the sidebar to switch between Movies and Series."""
self.create_sidebar_label("Movies", self.show_movies, pady=100)
self.create_sidebar_label("Series", self.show_series, pady=0)
def clear_content(self) -> None:
"""Clear the content frame by destroying the tree and scrollbar if they exist."""
for widget in [self.tree, self.scrollbar]:
if widget:
widget.destroy()
self.tree = None
self.scrollbar = None
def setup_treeview(self, columns: list, headings: list) -> None:
"""Set up the Treeview widget with specified columns and headings."""
self.tree = ttk.Treeview(
self.content,
columns=columns,
show='headings',
selectmode='browse',
style="Custom.Treeview"
)
for col, head in zip(columns, headings):
self.tree.heading(col, text=head, anchor='center')
anchor = 'w' if head.lower() == 'notes' else 'center'
width = 300 if head.lower() == 'notes' else 100 if head in self.BOOLEAN_COLUMNS.get(self.current_table, []) else 150
self.tree.column(col, width=width, anchor=anchor)
def load_movie_data(self) -> None:
"""Load and display movie data in the Treeview."""
self.clear_content()
columns = ["Movie", "Year", "Present", "Watched", "Notes"]
self.setup_treeview(columns, columns)
self.current_table = 'movies'
self.update_header("Movies")
for row in run_query('SELECT * FROM movies'):
record_id, movie, year, present, watched, notes = row
display_row = [
movie,
year,
self.bool_to_checkbox(present),
self.bool_to_checkbox(watched),
notes
]
self.tree.insert('', 'end', iid=str(record_id), values=display_row)
def load_series_data(self) -> None:
"""Load and display series data in the Treeview."""
self.clear_content()
columns = ["Series", "Seasons", "Year", "Present",
"Seasons Present", "Complete", "Watched",
"Seasons Seen", "Notes"]
self.setup_treeview(columns, columns)
self.current_table = 'series'
self.update_header("Series")
for row in run_query('SELECT * FROM series'):
(record_id, series, seasons, year, present, seasons_present,
complete, watched, seasons_seen, notes) = row
display_row = [
series,
seasons,
year,
self.bool_to_checkbox(present),
seasons_present,
self.bool_to_checkbox(complete),
self.bool_to_checkbox(watched),
seasons_seen,
notes
]
self.tree.insert('', 'end', iid=str(record_id), values=display_row)
def show_movies(self) -> None:
"""Display the movies table."""
self.load_movie_data()
def show_series(self) -> None:
"""Display the series table."""
self.load_series_data()
def add_entry(self) -> None:
"""Add a new entry to the current table."""
if self.current_table == 'movies':
run_query(
"INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', False, False, '')
)
self.load_movie_data()
elif self.current_table == 'series':
run_query(
"""INSERT INTO series
(series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
('', '', '', False, '', False, False, '', '')
)
self.load_series_data()
def delete_entry(self) -> None:
"""Delete the selected entry from the current table."""
selected_item = self.tree.selection()
if not selected_item:
messagebox.showwarning("No selection", "Please select a row to delete.")
return
code
row_id = selected_item[0]
run_query(f"DELETE FROM {self.current_table} WHERE id = ?", (row_id,))
if self.current_table == 'movies':
self.load_movie_data()
elif self.current_table == 'series':
self.load_series_data()
def on_row_select(self, event) -> None:
"""Handle the selection of a row in the Treeview."""
selected_item = self.tree.selection()
self.current_row_id = selected_item[0] if selected_item else None
def on_single_click(self, event) -> None:
"""Handle single click events for toggling boolean fields."""
region = self.tree.identify("region", event.x, event.y)
if region != "cell":
return
code
row_id = self.tree.identify_row(event.y)
column = self.tree.identify_column(event.x)
if not row_id or not column:
return
try:
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
except (IndexError, ValueError):
return
if column_name in self.BOOLEAN_COLUMNS.get(self.current_table, []):
current_value = self.tree.set(row_id, column_name)
new_value = not self.checkbox_to_bool(current_value)
self.tree.set(row_id, column_name, self.bool_to_checkbox(new_value))
row_values = self.tree.item(row_id)['values']
self.update_database(row_values)
def update_database(self, row_values: list) -> None:
"""Update the database with the modified row values."""
if self.current_table == 'movies':
query = """
UPDATE movies
SET movie = ?, year = ?, present = ?, watched = ?, notes = ?
WHERE id = ?
"""
parameters = (
row_values[0],
row_values[1],
self.checkbox_to_bool(row_values[2]),
self.checkbox_to_bool(row_values[3]),
row_values[4],
self.current_row_id
)
elif self.current_table == 'series':
query = """
UPDATE series
SET series = ?, seasons = ?, year = ?, present = ?, seasons_present = ?,
complete = ?, watched = ?, seasons_seen = ?, notes = ?
WHERE id = ?
"""
parameters = (
row_values[0],
row_values[1],
row_values[2],
self.checkbox_to_bool(row_values[3]),
row_values[4],
self.checkbox_to_bool(row_values[5]),
self.checkbox_to_bool(row_values[6]),
row_values[7],
row_values[8],
self.current_row_id
)
run_query(query, parameters)
def treeview_click_cursor(self, event) -> None:
"""Change the cursor to a hand when hovering over boolean columns."""
region = self.tree.identify("region", event.x, event.y)
if region == "cell":
column = self.tree.identify_column(event.x)
try:
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
cursor = "hand2" if column_name in self.BOOLEAN_COLUMNS.get(self.current_table, []) else ""
self.tree.configure(cursor=cursor)
except (IndexError, ValueError):
self.tree.configure(cursor="")
else:
self.tree.configure(cursor="")
@staticmethod
def bool_to_checkbox(value: bool) -> str:
"""Convert a boolean value to a checkbox symbol."""
return '☑' if value else '☐'
@staticmethod
def checkbox_to_bool(value: str) -> bool:
"""Convert a checkbox symbol to a boolean value."""
return value == '☑'
if name == "main":
create_tables()
app = MediaTracker()
app.mainloop()
Assistant
To modify the buttons (plus and minus) so that they are vertical to each other in a line (with the minus button on the left and the plus button on the right), and to move the buttons to the top of the sidebar, you need to make some adjustments to the _create_buttons method in your MediaTracker class. Here's how you can achieve that:
Step-by-Step Modifications:
Modify Button Layout: Adjust the layout of the buttons to be aligned horizontally rather than vertically.
Relocate Buttons: Move the button frame to the top of the sidebar instead of the spacer.
Here is the revised _create_buttons method and its positioning logic:
python
def _create_buttons(self) -> None:
"""Create add and delete buttons at the top of the sidebar."""
# Configure button styles
style = ttk.Style()
style.configure("Square.TButton",
font=('Arial', 14),
padding=(1, 1),
width=2,
background='white',
borderwidth=0,
relief='flat')
style.map("Square.TButton",
background=[('active', '#EAEDEF')])
# Create a frame for buttons at the top of the sidebar
button_frame = tk.Frame(self.sidebar, bg='#F7F8FC')
button_frame.pack(anchor='n', pady=10) # Adjust anchor and padding as needed
# Create delete and add buttons with a horizontal layout
delete_button = ttk.Button(
button_frame,
text="-",
command=self.delete_entry,
style="Square.TButton"
)
delete_button.pack(side='left', padx=5) # Place delete button on the left
add_button = ttk.Button(
button_frame,
text="+",
command=self.add_entry,
style="Square.TButton"
)
add_button.pack(side='left') # Place add button to the right of delete button
User
move the buttons above the text (Movies)
Assistant
To move the buttons above the "Movies" label in the sidebar, you need to adjust the order in which you create and pack the widgets within the sidebar frame. Here’s how you can do it:
Adjustments Needed:
Create the Buttons Before Labels: Place the buttons above the label by configuring the buttons and packing them before you set up the labels in the sidebar.
Ensure Proper Packing Order: The packing order in a frame determines the visual order of elements, so the buttons need to be packed before the labels.
Here's how you can modify the _create_widgets and _create_buttons methods:
python
def _create_widgets(self) -> None:
"""Create and layout all the widgets in the application."""
self.header_canvas = tk.Canvas(self, bg='white', highlightthickness=0, height=100)
self.header_canvas.grid(row=0, column=1, columnspan=3, sticky='ew')
self.header_canvas.grid_propagate(False)
self.update_header("Movies")
sidebar = tk.Frame(self, width=150, bg='#F7F8FC')
sidebar.grid(row=0, column=0, rowspan=2, sticky='ns')
sidebar.grid_propagate(False)
self.sidebar = sidebar
spacer = tk.Frame(self, width=100, bg='white')
spacer.grid(row=1, column=1, sticky='ns')
spacer.grid_propagate(False)
self.spacer = spacer
content = tk.Frame(self, bg='white')
content.grid(row=1, column=2, sticky='nsew')
self.content = content
self._create_buttons() # Create buttons first
self._create_sidebar_labels() # Then create labels below
def _create_buttons(self) -> None:
"""Create add and delete buttons at the top of the sidebar."""
style = ttk.Style()
style.configure("Square.TButton",
font=('Arial', 14),
padding=(1, 1),
width=2,
background='white',
borderwidth=0,
relief='flat')
style.map("Square.TButton",
background=[('active', '#EAEDEF')])
button_frame = tk.Frame(self.sidebar, bg='#F7F8FC') # Use sidebar for the button frame
button_frame.pack(anchor='n', pady=10) # Adjust anchor and padding as needed
delete_button = ttk.Button(
button_frame,
text="-",
command=self.delete_entry,
style="Square.TButton"
)
delete_button.pack(side='left', padx=5) # Place delete button on the left
add_button = ttk.Button(
button_frame,
text="+",
command=self.add_entry,
style="Square.TButton"
)
add_button.pack(side='left') # Place add button to the right of delete button
def _create_sidebar_labels(self) -> None:
"""Create labels for the sidebar to switch between Movies and Series."""
self.create_sidebar_label("Movies", self.show_movies, pady=100)
self.create_sidebar_label("Series", self.show_series, pady=0)
User
add a way to edit the fields in the databse by cliking on it.
Assistant
To enable editing of database fields by clicking on a cell in the Treeview, you can do the following:
Add an Entry Widget for Editing:
Create a temporary entry widget that appears over the selected cell when it's clicked, allowing the user to edit its content.
Update Database on Editing:
Once the user finishes editing, update the underlying Treeview item and the database with the new value.
Let's integrate this capability into your application:
Step-by-Step Implementation
Add Entry Editing Capability: Implement logic to place an Entry widget over the Treeview cell on a double click.
Update the Database: Modify the database when the editing is complete.
Here is how you can add this functionality:
python
User
print the new code in full
Assistant
Certainly! Below is the complete revised code with the ability to edit fields in the Treeview by double-clicking on them. This version integrates the changes to add an Entry widget for cell editing and updates the database with the new values once editing is complete.
python
User
make the field that opens on double click flat and without border
Assistant
To make the Entry widget, which opens for editing on double click, appear flat and without a border, you need to configure its relief and borderwidth options. Here is how you can adjust the widget to achieve this look:
Set relief to flat: This will remove the 3D effect on the border.
Set borderwidth to 0: This will eliminate any visible border line.
Here's the updated part of the code implementing these changes:
python
def on_double_click(self, event) -> None:
"""Open an entry widget to edit the item on double-click."""
region = self.tree.identify("region", event.x, event.y)
if region != "cell":
return
column = self.tree.identify_column(event.x)
row_id = self.tree.identify_row(event.y)
if not row_id or not column:
return
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
# Create the entry widget to edit the selected cell
x, y, width, height = self.tree.bbox(row_id, column)
current_value = self.tree.set(row_id, column_name)
entry = tk.Entry(self.content, font=self.custom_font, relief='flat', borderwidth=0)
entry.place(x=x, y=y, width=width, height=height)
entry.insert(0, current_value)
entry.focus()
def on_focus_out(event):
new_value = entry.get()
# Update the Treeview with the new value
self.tree.set(row_id, column_name, new_value)
# Remove the entry widget
entry.destroy()
# Update the database
self.update_database_from_treeview()
entry.bind("<FocusOut>", on_focus_out)
entry.bind("<Return>", lambda event: on_focus_out(event)) # Update on Enter as well
Explanation:
relief='flat': This option makes the Entry widget have a flat appearance, removing the default raised or sunken look.
borderwidth=0: Removes the border, making the widget integrate seamlessly with the background, which can help in maintaining a consistent UI design.
By incorporating these options, the Entry widget that appears on a double-click will be flat and borderless, aligning with a minimalist or modern aesthetic often desired in UI design.
User
move the plus and minus buttons in the spacer bar and move there position in accordance with the row the user is in.
Assistant
To move the plus and minus buttons into the spacer bar and have them reposition according to the selected row in the Treeview, you will need to update your implementation to dynamically adjust the buttons' location.
Here’s how you can achieve this:
Create the Buttons in the Spacer Bar: Initialize the buttons within the spacer bar frame, not the sidebar.
Reposition Buttons Based on Selected Row: When a user selects a row in the Treeview, calculate the position of the row and move the buttons to that position.
Below is how you can implement these features:
Revised Implementation:
Step 1: Create the Buttons in the Spacer Bar
Update the _create_widgets and _create_buttons methods:
python
def _create_widgets(self) -> None:
"""Create and layout all the widgets in the application."""
self.header_canvas = tk.Canvas(self, bg='white', highlightthickness=0, height=100)
self.header_canvas.grid(row=0, column=1, columnspan=3, sticky='ew')
self.header_canvas.grid_propagate(False)
self.update_header("Movies")
sidebar = tk.Frame(self, width=150, bg='#F7F8FC')
sidebar.grid(row=0, column=0, rowspan=2, sticky='ns')
sidebar.grid_propagate(False)
self.sidebar = sidebar
spacer = tk.Frame(self, width=100, bg='white')
spacer.grid(row=1, column=1, sticky='ns')
spacer.grid_propagate(False)
self.spacer = spacer
content = tk.Frame(self, bg='white')
content.grid(row=1, column=2, sticky='nsew')
self.content = content
self._create_buttons() # Create buttons in spacer
self._create_sidebar_labels()
def _create_buttons(self) -> None:
"""Create add and delete buttons within the spacer."""
style = ttk.Style()
style.configure("Square.TButton",
font=('Arial', 14),
padding=(1, 1),
width=2,
background='white',
borderwidth=0,
relief='flat')
style.map("Square.TButton",
background=[('active', '#EAEDEF')])
# Note: No 'pack' or 'place' is done initially
self.add_button = ttk.Button(
self.spacer,
text="+",
command=self.add_entry,
style="Square.TButton"
)
self.delete_button = ttk.Button(
self.spacer,
text="-",
command=self.delete_entry,
style="Square.TButton"
)
User
print he new code in full
Assistant
Below is the complete revised code that places the plus and minus buttons in the spacer bar and repositions them according to the selected row in the Treeview:
python
User
flip the position of the minus and plus button
Assistant
To flip the positions of the minus and plus buttons, you just need to switch their place method calls in the on_row_select method so that the minus button appears on the left and the plus button on the right. Here's the updated code for the on_row_select function:
python
def on_row_select(self, event) -> None:
"""Handle the selection of a row in the Treeview."""
selected_item = self.tree.selection()
self.current_row_id = selected_item[0] if selected_item else None
if selected_item:
x, y, width, height = self.tree.bbox(self.current_row_id)
y_offset = y + height // 2
# Move buttons to align with the selected row, flipping their positions
self.delete_button.place(x=20, y=y_offset, anchor='center') # Minus button on the left
self.add_button.place(x=60, y=y_offset, anchor='center') # Plus button on the right
Explanation:
Minus Button (Delete): Placed on the left side by setting its x position to 20.
Plus Button (Add): Placed on the right side by setting its x position to 60.
These adjustments ensure the minus button appears before the plus button when aligned with the selected row in the Treeview. Feel free to adjust the x positions further to fit your layout needs.
User
add a notice to the delete button that informas the user that the action can not be redone an asks ton cancel or delete
Assistant
To add a confirmation dialog that informs users that the delete action cannot be undone and asks them to confirm or cancel the deletion, you can use the messagebox.askokcancel function from the tkinter library. This function creates a popup dialog with OK and Cancel options.
Below is an updated version of the delete_entry method, incorporating the confirmation dialog:
python
def delete_entry(self) -> None:
"""Delete the selected entry from the current table with confirmation."""
selected_item = self.tree.selection()
if not selected_item:
messagebox.showwarning("No selection", "Please select a row to delete.")
return
# Confirmation dialog
confirm = messagebox.askokcancel(
"Confirm Deletion",
"This action cannot be undone.\nDo you want to delete the selected entry?",
icon='warning'
)
if confirm:
row_id = selected_item[0]
run_query(f"DELETE FROM {self.current_table} WHERE id = ?", (row_id,))
if self.current_table == 'movies':
self.load_movie_data()
elif self.current_table == 'series':
self.load_series_data()
Explanation:
messagebox.askokcancel: This function creates a dialog box that prompts the user with a warning message and two buttons: OK and Cancel.
User Choice Handling: The confirm variable captures the user's response. If the user clicks "OK", the deletion proceeds. If they click "Cancel", the operation is aborted.
Icon: The icon='warning' option adds a warning icon to the dialog, emphasizing the importance of the user's decision.
By implementing this confirmation step, you provide users with a safeguard against accidental deletions, improving the application's robustness and user experience.
User
if no row is selected the plus and minus button should hide
Assistant
To hide the plus and minus buttons when no row is selected in the Treeview, you can use the place_forget() method to remove them from the view. This method will temporarily hide the buttons without destroying them, so they can be shown again when a row is selected.
Here’s how you can incorporate this functionality:
Updated on_row_select Method
python
def on_row_select(self, event) -> None:
"""Handle the selection of a row in the Treeview."""
selected_item = self.tree.selection()
self.current_row_id = selected_item[0] if selected_item else None
if selected_item:
x, y, width, height = self.tree.bbox(self.current_row_id)
y_offset = y + height // 2
# Move buttons to align with the selected row, flipping their positions
self.delete_button.place(x=20, y=y_offset, anchor='center') # Minus button on the left
self.add_button.place(x=60, y=y_offset, anchor='center') # Plus button on the right
else:
# Hide buttons if no row is selected
self.delete_button.place_forget()
self.add_button.place_forget()
Explanation:
Checking Selection: The method checks if any item is selected with self.tree.selection().
Show Buttons: If a row is selected, it places the buttons using the place() method, positioning them relative to the selected row.
Hide Buttons: If no row is selected (selected_item is empty or None), it uses place_forget() on both buttons to hide them from view.
This approach dynamically adjusts the visibility of the buttons based on user interaction, ensuring they are only visible when there is a context (i.e., a selected row) for their actions.
User
the row should be unselected when i click on something elses with the mouse. And the button should hide
Assistant
To unselect a row and hide the buttons when the user clicks outside the Treeview, it’s necessary to detect clicks outside of the Treeview area and then clear the selection. This can be accomplished by binding a mouse click event on the Treeview and checking if the click is outside a row. If so, deselect all current selections and hide the buttons.
Here’s how you can implement this behavior:
Step-by-Step Implementation
Bind the Mouse Click Event: Capture click events on the entire application window.
Check If Click Is Outside Treeview Row: Determine if the click is not on a valid treeview row.
Deselect and Hide: Deselect any selected row and hide the buttons if the click is outside.
Implementation
Below is the updated code for handling deselection and button hiding:
python
class MediaTracker(tk.Tk):
# ... existing code ...
def clear_selection(self):
"""Clears the treeview selection and hides the buttons."""
# Deselect any selected items
self.tree.selection_remove(self.tree.selection())
self.current_row_id = None
# Hide buttons
self.delete_button.place_forget()
self.add_button.place_forget()
def bind_events(self):
"""Bind necessary events for the treeview."""
# Bind to clicks on the treeview but outside of a row to clear selection
self.tree.bind("<Button-1>", self.on_click, add="+")
# Bind to any click on the window to potentially clear selection
self.bind("<Button-1>", self.on_click, add="+")
def on_click(self, event):
"""Handle clicks to manage selection and button visibility."""
widget_clicked = event.widget
# Check if the click is outside of the Treeview
if widget_clicked != self.tree:
self.clear_selection()
else:
row_id = self.tree.identify_row(event.y)
if not row_id:
self.clear_selection()
def _create_widgets(self) -> None:
"""Create and layout all the widgets in the application."""
# ... existing widget creation code ...
self._create_buttons() # Create buttons in spacer
self._create_sidebar_labels()
self.bind_events() # Bind events for managing selection and clicking outside the treeview
# ... rest of the class code remains unchanged ...
User
print the new code in full
Assistant
Certainly! Below is the full code with the functionality to deselect the row and hide the buttons when clicking outside of the Treeview or if the click is on an area of the Treeview that doesn't correspond to a valid row:
Button Alignment: The pack() method's side option is used to align buttons horizontally by setting side='left' for each button within the button frame.
Button Frame Location: The button_frame is now a part of self.sidebar and is packed at the top (anchor='n') of the sidebar with some vertical padding (pady=10) for aesthetic spacing.
Removing Old Placements: Ensure the earlier button pack layout using vertical alignment within self.spacer is removed or adjusted according to this new layout.
This modification ensures the buttons are repositioned as specified and enhances the usability of the GUI by placing essential controls in a more accessible location. Adjustments like padding or side alignment (padx=5) can be tweaked further as per the specific design needs.
Explanation:
Button Creation: The _create_buttons() method is called before _create_sidebar_labels() in _create_widgets(). This ensures that the buttons will be visually placed above the text labels in the sidebar.
Packing Adjustment: The buttons are packed with anchor='n' to align them at the top of self.sidebar. You can adjust the pady value to control the vertical spacing.
By following these steps, the buttons will appear above the "Movies" label in your sidebar, contributing to a more intuitive and organized layout.
def on_double_click(self, event) -> None:
"""Open an entry widget to edit the item on double-click."""
region = self.tree.identify("region", event.x, event.y)
if region != "cell":
return
column = self.tree.identify_column(event.x)
row_id = self.tree.identify_row(event.y)
if not row_id or not column:
return
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
# Create the entry widget to edit the selected cell
x, y, width, height = self.tree.bbox(row_id, column)
current_value = self.tree.set(row_id, column_name)
entry = tk.Entry(self.content, font=self.custom_font)
entry.place(x=x, y=y, width=width, height=height)
entry.insert(0, current_value)
entry.focus()
def on_focus_out(event):
new_value = entry.get()
# Update the Treeview with the new value
self.tree.set(row_id, column_name, new_value)
# Remove the entry widget
entry.destroy()
# Update the database
self.update_database_from_treeview()
entry.bind("<FocusOut>", on_focus_out)
entry.bind("<Return>", lambda event: on_focus_out(event)) # Update on Enter as well
def update_database_from_treeview(self):
"""Update database with values from the Treeview."""
for row_id in self.tree.get_children():
row_values = self.tree.item(row_id)['values']
self.current_row_id = row_id # Needed for update_database function
self.update_database(row_values)
# Bind the double-click event to the Treeview
def setup_treeview(self, columns: list, headings: list) -> None:
"""Set up the Treeview widget with specified columns and headings."""
self.tree = ttk.Treeview(
self.content,
columns=columns,
show='headings',
selectmode='browse',
style="Custom.Treeview"
)
for col, head in zip(columns, headings):
self.tree.heading(col, text=head, anchor='center')
anchor = 'w' if head.lower() == 'notes' else 'center'
width = 300 if head.lower() == 'notes' else 100 if head in self.BOOLEAN_COLUMNS.get(self.current_table, []) else 150
self.tree.column(col, width=width, anchor=anchor)
self.scrollbar = ttk.Scrollbar(
self.content,
orient="vertical",
command=self.tree.yview,
style="Custom.Vertical.TScrollbar" # Use the custom style
)
self.tree.configure(yscrollcommand=self.scrollbar.set)
self.scrollbar.pack(side='right', fill='y')
self.tree.pack(fill='both', expand=True)
self.tree.bind('<<TreeviewSelect>>', self.on_row_select)
self.tree.bind('<Button-1>', self.on_single_click)
self.tree.bind("<Double-Button-1>", self.on_double_click) # Bind double-click event
self.tree.bind("<Motion>", self.treeview_click_cursor)
Explanation:
Double-Click to Edit (on_double_click): The method identifies which cell is clicked, creates an Entry widget positioned over the cell, pre-fills it with the current cell value, and allows the user to modify it.
Focus-Out/Enter to Save: The method on_focus_out captures the new value when editing is complete (focus leaves the entry field or Enter is pressed), updates the Treeview, and triggers the database update.
Database Update (update_database_from_treeview): This method retrieves data from all rows in the Treeview to reflect all changes in the database.
This approach allows a user to simply double-click on a cell to initiate editing, providing a user-friendly way to modify entries directly in the application.
import sys
import sqlite3
from pathlib import Path
import tkinter as tk
from tkinter import ttk, messagebox, font
MEDIA_DB = Path(__file__).parent / 'media.db'
if sys.platform.startswith('win'):
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print("Error setting DPI awareness:", e)
def run_query(query: str, parameters: tuple = ()) -> list:
"""Execute a SQL query and return the results if it's a SELECT statement."""
with sqlite3.connect(MEDIA_DB) as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
if query.strip().lower().startswith("select"):
return result.fetchall()
conn.commit()
def create_tables() -> None:
"""Create the movies and series tables in the database if they do not exist."""
run_query('''
CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
movie TEXT,
year TEXT,
present BOOLEAN,
watched BOOLEAN,
notes TEXT
);
''')
run_query('''
CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
series TEXT,
seasons TEXT,
year TEXT,
present BOOLEAN,
seasons_present TEXT,
complete BOOLEAN,
watched BOOLEAN,
seasons_seen TEXT,
notes TEXT
);
''')
class MediaTracker(tk.Tk):
"""A Tkinter application to track movies and series."""
BOOLEAN_COLUMNS = {
'movies': ['Present', 'Watched'],
'series': ['Present', 'Complete', 'Watched']
}
def __init__(self):
super().__init__()
self.configure(bg='white')
self.title("Movies and Series Tracker")
self.geometry("1200x600")
self.custom_font = self._get_custom_font()
self.current_table = None
self.current_row_id = None
self.tree = None
self.scrollbar = None
self._configure_style()
self._configure_scrollbar_style() # Configure scrollbar styles
self._configure_grid()
self._create_widgets()
self.show_movies()
def _get_custom_font(self) -> font.Font:
"""Retrieve the custom font, defaulting to Arial if Literata is unavailable."""
try:
return font.Font(family='Literata', size=12)
except:
return font.Font(family='Arial', size=12)
def _configure_style(self) -> None:
"""Configure the styles for Treeview and buttons."""
font_line_space = self.custom_font.metrics('linespace')
row_height = font_line_space + 4
style = ttk.Style()
style.theme_use("default")
style.layout(
'Custom.Treeview',
[('Custom.Treeview.treearea', {'sticky': 'nsew'})]
)
style.configure(
"Custom.Treeview",
font=self.custom_font,
rowheight=row_height,
borderwidth=0,
relief='flat',
highlightthickness=0,
background='white',
fieldbackground='white'
)
style.configure(
"Custom.Treeview.Heading",
font=(self.custom_font.cget("family"), self.custom_font.cget("size"), "bold"),
background='#F7F8FC',
relief='solid',
borderwidth=0,
anchor='center'
)
style.map(
"Custom.Treeview.Heading",
background=[('active', 'white')],
relief=[('active', 'solid')]
)
style.configure("Custom.TButton", font=self.custom_font)
def _configure_scrollbar_style(self) -> None:
"""Configure the style for Scrollbars."""
style = ttk.Style()
style.theme_use("default")
style.configure("Custom.Vertical.TScrollbar",
troughcolor='white',
background='#c6c6c6',
bordercolor='white',
arrowcolor='white',
borderwidth=0,
relief='flat')
style.map("Custom.Vertical.TScrollbar",
background=[('active', '#9b9b9b'), ('pressed', '#8b8b8bff')])
style.layout('Custom.Vertical.TScrollbar',
[('Vertical.Scrollbar.trough',
{'children': [('Vertical.Scrollbar.thumb', {'expand': '1',
'sticky': 'nswe'})],
'sticky': 'ns'})])
def _configure_grid(self) -> None:
"""Configure the grid layout for the main window."""
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(2, weight=1)
def _create_widgets(self) -> None:
"""Create and layout all the widgets in the application."""
self.header_canvas = tk.Canvas(self, bg='white', highlightthickness=0, height=100)
self.header_canvas.grid(row=0, column=1, columnspan=3, sticky='ew')
self.header_canvas.grid_propagate(False)
self.update_header("Movies")
sidebar = tk.Frame(self, width=150, bg='#F7F8FC')
sidebar.grid(row=0, column=0, rowspan=2, sticky='ns')
sidebar.grid_propagate(False)
self.sidebar = sidebar
spacer = tk.Frame(self, width=100, bg='white')
spacer.grid(row=1, column=1, sticky='ns')
spacer.grid_propagate(False)
self.spacer = spacer
content = tk.Frame(self, bg='white')
content.grid(row=1, column=2, sticky='nsew')
self.content = content
self._create_buttons() # Create buttons first
self._create_sidebar_labels() # Then create labels below
def update_header(self, text: str) -> None:
"""Update the header with the given text."""
self.header_canvas.delete("all")
small_font = font.Font(family=self.custom_font.actual('family'), size=10)
self.header_canvas.create_text(
10, 10,
anchor='nw',
text="Data >",
fill='#999999',
font=small_font
)
self.header_canvas.create_text(
80, 10,
anchor='nw',
text=text,
fill='black',
font=small_font
)
def _create_sidebar_labels(self) -> None:
"""Create labels for the sidebar to switch between Movies and Series."""
self.create_sidebar_label("Movies", self.show_movies, pady=100)
self.create_sidebar_label("Series", self.show_series, pady=0)
def create_sidebar_label(self, text: str, command, pady=0) -> None:
"""Create a clickable label in the sidebar."""
label = tk.Label(
self.sidebar,
text=text,
bg='#F7F8FC',
font=self.custom_font,
cursor="hand2",
anchor='w',
padx=50,
pady=0
)
label.pack(pady=(pady, 1), fill='x')
label.bind("<Enter>", lambda e: label.config(bg='#EAEDEF'))
label.bind("<Leave>", lambda e: label.config(bg='#F7F8FC'))
label.bind("<Button-1>", lambda e: command())
def _create_buttons(self) -> None:
"""Create add and delete buttons at the top of the sidebar."""
style = ttk.Style()
style.configure("Square.TButton",
font=('Arial', 14),
padding=(1, 1),
width=2,
background='white',
borderwidth=0,
relief='flat')
style.map("Square.TButton",
background=[('active', '#EAEDEF')])
button_frame = tk.Frame(self.sidebar, bg='#F7F8FC')
button_frame.pack(anchor='n', pady=10) # Adjust anchor and padding as needed
delete_button = ttk.Button(
button_frame,
text="-",
command=self.delete_entry,
style="Square.TButton"
)
delete_button.pack(side='left', padx=5) # Place delete button on the left
add_button = ttk.Button(
button_frame,
text="+",
command=self.add_entry,
style="Square.TButton"
)
add_button.pack(side='left') # Place add button to the right of delete button
def clear_content(self) -> None:
"""Clear the content frame by destroying the tree and scrollbar if they exist."""
for widget in [self.tree, self.scrollbar]:
if widget:
widget.destroy()
self.tree = None
self.scrollbar = None
def setup_treeview(self, columns: list, headings: list) -> None:
"""Set up the Treeview widget with specified columns and headings."""
self.tree = ttk.Treeview(
self.content,
columns=columns,
show='headings',
selectmode='browse',
style="Custom.Treeview"
)
for col, head in zip(columns, headings):
self.tree.heading(col, text=head, anchor='center')
anchor = 'w' if head.lower() == 'notes' else 'center'
width = 300 if head.lower() == 'notes' else 100 if head in self.BOOLEAN_COLUMNS.get(self.current_table, []) else 150
self.tree.column(col, width=width, anchor=anchor)
self.scrollbar = ttk.Scrollbar(
self.content,
orient="vertical",
command=self.tree.yview,
style="Custom.Vertical.TScrollbar" # Use the custom style
)
self.tree.configure(yscrollcommand=self.scrollbar.set)
self.scrollbar.pack(side='right', fill='y')
self.tree.pack(fill='both', expand=True)
self.tree.bind('<<TreeviewSelect>>', self.on_row_select)
self.tree.bind('<Button-1>', self.on_single_click)
self.tree.bind("<Double-Button-1>", self.on_double_click) # Bind double-click event
self.tree.bind("<Motion>", self.treeview_click_cursor)
def load_movie_data(self) -> None:
"""Load and display movie data in the Treeview."""
self.clear_content()
columns = ["Movie", "Year", "Present", "Watched", "Notes"]
self.setup_treeview(columns, columns)
self.current_table = 'movies'
self.update_header("Movies")
for row in run_query('SELECT * FROM movies'):
record_id, movie, year, present, watched, notes = row
display_row = [
movie,
year,
self.bool_to_checkbox(present),
self.bool_to_checkbox(watched),
notes
]
self.tree.insert('', 'end', iid=str(record_id), values=display_row)
def load_series_data(self) -> None:
"""Load and display series data in the Treeview."""
self.clear_content()
columns = ["Series", "Seasons", "Year", "Present",
"Seasons Present", "Complete", "Watched",
"Seasons Seen", "Notes"]
self.setup_treeview(columns, columns)
self.current_table = 'series'
self.update_header("Series")
for row in run_query('SELECT * FROM series'):
(record_id, series, seasons, year, present, seasons_present,
complete, watched, seasons_seen, notes) = row
display_row = [
series,
seasons,
year,
self.bool_to_checkbox(present),
seasons_present,
self.bool_to_checkbox(complete),
self.bool_to_checkbox(watched),
seasons_seen,
notes
]
self.tree.insert('', 'end', iid=str(record_id), values=display_row)
def show_movies(self) -> None:
"""Display the movies table."""
self.load_movie_data()
def show_series(self) -> None:
"""Display the series table."""
self.load_series_data()
def add_entry(self) -> None:
"""Add a new entry to the current table."""
if self.current_table == 'movies':
run_query(
"INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', False, False, '')
)
self.load_movie_data()
elif self.current_table == 'series':
run_query(
"""INSERT INTO series
(series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
('', '', '', False, '', False, False, '', '')
)
self.load_series_data()
def delete_entry(self) -> None:
"""Delete the selected entry from the current table."""
selected_item = self.tree.selection()
if not selected_item:
messagebox.showwarning("No selection", "Please select a row to delete.")
return
row_id = selected_item[0]
run_query(f"DELETE FROM {self.current_table} WHERE id = ?", (row_id,))
if self.current_table == 'movies':
self.load_movie_data()
elif self.current_table == 'series':
self.load_series_data()
def on_row_select(self, event) -> None:
"""Handle the selection of a row in the Treeview."""
selected_item = self.tree.selection()
self.current_row_id = selected_item[0] if selected_item else None
def on_single_click(self, event) -> None:
"""Handle single click events for toggling boolean fields."""
region = self.tree.identify("region", event.x, event.y)
if region != "cell":
return
row_id = self.tree.identify_row(event.y)
column = self.tree.identify_column(event.x)
if not row_id or not column:
return
try:
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
except (IndexError, ValueError):
return
if column_name in self.BOOLEAN_COLUMNS.get(self.current_table, []):
current_value = self.tree.set(row_id, column_name)
new_value = not self.checkbox_to_bool(current_value)
self.tree.set(row_id, column_name, self.bool_to_checkbox(new_value))
row_values = self.tree.item(row_id)['values']
self.update_database(row_values)
def on_double_click(self, event) -> None:
"""Open an entry widget to edit the item on double-click."""
region = self.tree.identify("region", event.x, event.y)
if region != "cell":
return
column = self.tree.identify_column(event.x)
row_id = self.tree.identify_row(event.y)
if not row_id or not column:
return
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
# Create the entry widget to edit the selected cell
x, y, width, height = self.tree.bbox(row_id, column)
current_value = self.tree.set(row_id, column_name)
entry = tk.Entry(self.content, font=self.custom_font)
entry.place(x=x, y=y, width=width, height=height)
entry.insert(0, current_value)
entry.focus()
def on_focus_out(event):
new_value = entry.get()
# Update the Treeview with the new value
self.tree.set(row_id, column_name, new_value)
# Remove the entry widget
entry.destroy()
# Update the database
self.update_database_from_treeview()
entry.bind("<FocusOut>", on_focus_out)
entry.bind("<Return>", lambda event: on_focus_out(event)) # Update on Enter as well
def update_database(self, row_values: list) -> None:
"""Update the database with the modified row values."""
if self.current_table == 'movies':
query = """
UPDATE movies
SET movie = ?, year = ?, present = ?, watched = ?, notes = ?
WHERE id = ?
"""
parameters = (
row_values[0],
row_values[1],
self.checkbox_to_bool(row_values[2]),
self.checkbox_to_bool(row_values[3]),
row_values[4],
self.current_row_id
)
elif self.current_table == 'series':
query = """
UPDATE series
SET series = ?, seasons = ?, year = ?, present = ?, seasons_present = ?,
complete = ?, watched = ?, seasons_seen = ?, notes = ?
WHERE id = ?
"""
parameters = (
row_values[0],
row_values[1],
row_values[2],
self.checkbox_to_bool(row_values[3]),
row_values[4],
self.checkbox_to_bool(row_values[5]),
self.checkbox_to_bool(row_values[6]),
row_values[7],
row_values[8],
self.current_row_id
)
run_query(query, parameters)
def update_database_from_treeview(self):
"""Update database with values from the Treeview."""
for row_id in self.tree.get_children():
row_values = self.tree.item(row_id)['values']
self.current_row_id = row_id # Needed for update_database function
self.update_database(row_values)
def treeview_click_cursor(self, event) -> None:
"""Change the cursor to a hand when hovering over boolean columns."""
region = self.tree.identify("region", event.x, event.y)
if region == "cell":
column = self.tree.identify_column(event.x)
try:
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
cursor = "hand2" if column_name in self.BOOLEAN_COLUMNS.get(self.current_table, []) else ""
self.tree.configure(cursor=cursor)
except (IndexError, ValueError):
self.tree.configure(cursor="")
else:
self.tree.configure(cursor="")
@staticmethod
def bool_to_checkbox(value: bool) -> str:
"""Convert a boolean value to a checkbox symbol."""
return '☑' if value else '☐'
@staticmethod
def checkbox_to_bool(value: str) -> bool:
"""Convert a checkbox symbol to a boolean value."""
return value == '☑'
if __name__ == "__main__":
create_tables()
app = MediaTracker()
app.mainloop()
Key Features:
Editable Cells: Double-click a cell in the Treeview to make it editable. An Entry widget overlays the cell for inline editing.
Focus-Out and Enter to Save: Changes are saved to the Treeview and database after the Entry loses focus or when the Enter key is pressed.
Dynamic Database Update: The database is updated to reflect changes made in the Treeview for both "movies" and "series" tables.
This code creates a user-friendly interface where database field values can be edited directly in the application, maintaining synchronization between the displayed data and the actual database.
Step 2: Position Buttons Based on Row Selection
Update the on_row_select to dynamically position the buttons:
python
def on_row_select(self, event) -> None:
"""Handle the selection of a row in the Treeview."""
selected_item = self.tree.selection()
self.current_row_id = selected_item[0] if selected_item else None
if selected_item:
x, y, width, height = self.tree.bbox(self.current_row_id)
y_offset = y + height // 2
# Move buttons to align with the selected row
self.add_button.place(x=20, y=y_offset, anchor='center') # Adjust x as needed
self.delete_button.place(x=60, y=y_offset, anchor='center') # Adjust x as needed
Explanation:
Button Initialization in Spacer: The buttons are created within self.spacer but are not initially placed. They are instead dynamically placed based on the selected row.
Dynamic Positioning: When a row is selected (on_row_select), the buttons (add_button and delete_button) are repositioned in the spacer frame to align with the middle of the selected row (y_offset = y + height // 2).
Anchor Adjustment: Using anchor='center' helps position the buttons relative to their middle point on the y-axis, providing consistency when moving them vertically.
This approach makes sure the buttons are conveniently positioned for user interaction, responding dynamically to the selected treeview row. Adjust the x positions further if needed to fit the UI design better.
import sys
import sqlite3
from pathlib import Path
import tkinter as tk
from tkinter import ttk, messagebox, font
MEDIA_DB = Path(__file__).parent / 'media.db'
if sys.platform.startswith('win'):
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print("Error setting DPI awareness:", e)
def run_query(query: str, parameters: tuple = ()) -> list:
"""Execute a SQL query and return the results if it's a SELECT statement."""
with sqlite3.connect(MEDIA_DB) as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
if query.strip().lower().startswith("select"):
return result.fetchall()
conn.commit()
def create_tables() -> None:
"""Create the movies and series tables in the database if they do not exist."""
run_query('''
CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
movie TEXT,
year TEXT,
present BOOLEAN,
watched BOOLEAN,
notes TEXT
);
''')
run_query('''
CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
series TEXT,
seasons TEXT,
year TEXT,
present BOOLEAN,
seasons_present TEXT,
complete BOOLEAN,
watched BOOLEAN,
seasons_seen TEXT,
notes TEXT
);
''')
class MediaTracker(tk.Tk):
"""A Tkinter application to track movies and series."""
BOOLEAN_COLUMNS = {
'movies': ['Present', 'Watched'],
'series': ['Present', 'Complete', 'Watched']
}
def __init__(self):
super().__init__()
self.configure(bg='white')
self.title("Movies and Series Tracker")
self.geometry("1200x600")
self.custom_font = self._get_custom_font()
self.current_table = None
self.current_row_id = None
self.tree = None
self.scrollbar = None
self._configure_style()
self._configure_scrollbar_style() # Configure scrollbar styles
self._configure_grid()
self._create_widgets()
self.show_movies()
def _get_custom_font(self) -> font.Font:
"""Retrieve the custom font, defaulting to Arial if Literata is unavailable."""
try:
return font.Font(family='Literata', size=12)
except:
return font.Font(family='Arial', size=12)
def _configure_style(self) -> None:
"""Configure the styles for Treeview and buttons."""
font_line_space = self.custom_font.metrics('linespace')
row_height = font_line_space + 4
style = ttk.Style()
style.theme_use("default")
style.layout(
'Custom.Treeview',
[('Custom.Treeview.treearea', {'sticky': 'nsew'})]
)
style.configure(
"Custom.Treeview",
font=self.custom_font,
rowheight=row_height,
borderwidth=0,
relief='flat',
highlightthickness=0,
background='white',
fieldbackground='white'
)
style.configure(
"Custom.Treeview.Heading",
font=(self.custom_font.cget("family"), self.custom_font.cget("size"), "bold"),
background='#F7F8FC',
relief='solid',
borderwidth=0,
anchor='center'
)
style.map(
"Custom.Treeview.Heading",
background=[('active', 'white')],
relief=[('active', 'solid')]
)
style.configure("Custom.TButton", font=self.custom_font)
def _configure_scrollbar_style(self) -> None:
"""Configure the style for Scrollbars."""
style = ttk.Style()
style.theme_use("default")
style.configure("Custom.Vertical.TScrollbar",
troughcolor='white',
background='#c6c6c6',
bordercolor='white',
arrowcolor='white',
borderwidth=0,
relief='flat')
style.map("Custom.Vertical.TScrollbar",
background=[('active', '#9b9b9b'), ('pressed', '#8b8b8bff')])
style.layout('Custom.Vertical.TScrollbar',
[('Vertical.Scrollbar.trough',
{'children': [('Vertical.Scrollbar.thumb', {'expand': '1',
'sticky': 'nswe'})],
'sticky': 'ns'})])
def _configure_grid(self) -> None:
"""Configure the grid layout for the main window."""
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(2, weight=1)
def _create_widgets(self) -> None:
"""Create and layout all the widgets in the application."""
self.header_canvas = tk.Canvas(self, bg='white', highlightthickness=0, height=100)
self.header_canvas.grid(row=0, column=1, columnspan=3, sticky='ew')
self.header_canvas.grid_propagate(False)
self.update_header("Movies")
sidebar = tk.Frame(self, width=150, bg='#F7F8FC')
sidebar.grid(row=0, column=0, rowspan=2, sticky='ns')
sidebar.grid_propagate(False)
self.sidebar = sidebar
spacer = tk.Frame(self, width=100, bg='white')
spacer.grid(row=1, column=1, sticky='ns')
spacer.grid_propagate(False)
self.spacer = spacer
content = tk.Frame(self, bg='white')
content.grid(row=1, column=2, sticky='nsew')
self.content = content
self._create_buttons() # Create buttons in spacer
self._create_sidebar_labels()
def update_header(self, text: str) -> None:
"""Update the header with the given text."""
self.header_canvas.delete("all")
small_font = font.Font(family=self.custom_font.actual('family'), size=10)
self.header_canvas.create_text(
10, 10,
anchor='nw',
text="Data >",
fill='#999999',
font=small_font
)
self.header_canvas.create_text(
80, 10,
anchor='nw',
text=text,
fill='black',
font=small_font
)
def _create_sidebar_labels(self) -> None:
"""Create labels for the sidebar to switch between Movies and Series."""
self.create_sidebar_label("Movies", self.show_movies, pady=100)
self.create_sidebar_label("Series", self.show_series, pady=0)
def create_sidebar_label(self, text: str, command, pady=0) -> None:
"""Create a clickable label in the sidebar."""
label = tk.Label(
self.sidebar,
text=text,
bg='#F7F8FC',
font=self.custom_font,
cursor="hand2",
anchor='w',
padx=50,
pady=0
)
label.pack(pady=(pady, 1), fill='x')
label.bind("<Enter>", lambda e: label.config(bg='#EAEDEF'))
label.bind("<Leave>", lambda e: label.config(bg='#F7F8FC'))
label.bind("<Button-1>", lambda e: command())
def _create_buttons(self) -> None:
"""Create add and delete buttons within the spacer."""
style = ttk.Style()
style.configure("Square.TButton",
font=('Arial', 14),
padding=(1, 1),
width=2,
background='white',
borderwidth=0,
relief='flat')
style.map("Square.TButton",
background=[('active', '#EAEDEF')])
# Initialize buttons but do not pack them initially
self.add_button = ttk.Button(
self.spacer,
text="+",
command=self.add_entry,
style="Square.TButton"
)
self.delete_button = ttk.Button(
self.spacer,
text="-",
command=self.delete_entry,
style="Square.TButton"
)
def clear_content(self) -> None:
"""Clear the content frame by destroying the tree and scrollbar if they exist."""
for widget in [self.tree, self.scrollbar]:
if widget:
widget.destroy()
self.tree = None
self.scrollbar = None
def setup_treeview(self, columns: list, headings: list) -> None:
"""Set up the Treeview widget with specified columns and headings."""
self.tree = ttk.Treeview(
self.content,
columns=columns,
show='headings',
selectmode='browse',
style="Custom.Treeview"
)
for col, head in zip(columns, headings):
self.tree.heading(col, text=head, anchor='center')
anchor = 'w' if head.lower() == 'notes' else 'center'
width = 300 if head.lower() == 'notes' else 100 if head in self.BOOLEAN_COLUMNS.get(self.current_table, []) else 150
self.tree.column(col, width=width, anchor=anchor)
self.scrollbar = ttk.Scrollbar(
self.content,
orient="vertical",
command=self.tree.yview,
style="Custom.Vertical.TScrollbar" # Use the custom style
)
self.tree.configure(yscrollcommand=self.scrollbar.set)
self.scrollbar.pack(side='right', fill='y')
self.tree.pack(fill='both', expand=True)
self.tree.bind('<<TreeviewSelect>>', self.on_row_select)
self.tree.bind('<Button-1>', self.on_single_click)
self.tree.bind("<Double-Button-1>", self.on_double_click) # Bind double-click event
self.tree.bind("<Motion>", self.treeview_click_cursor)
def load_movie_data(self) -> None:
"""Load and display movie data in the Treeview."""
self.clear_content()
columns = ["Movie", "Year", "Present", "Watched", "Notes"]
self.setup_treeview(columns, columns)
self.current_table = 'movies'
self.update_header("Movies")
for row in run_query('SELECT * FROM movies'):
record_id, movie, year, present, watched, notes = row
display_row = [
movie,
year,
self.bool_to_checkbox(present),
self.bool_to_checkbox(watched),
notes
]
self.tree.insert('', 'end', iid=str(record_id), values=display_row)
def load_series_data(self) -> None:
"""Load and display series data in the Treeview."""
self.clear_content()
columns = ["Series", "Seasons", "Year", "Present",
"Seasons Present", "Complete", "Watched",
"Seasons Seen", "Notes"]
self.setup_treeview(columns, columns)
self.current_table = 'series'
self.update_header("Series")
for row in run_query('SELECT * FROM series'):
(record_id, series, seasons, year, present, seasons_present,
complete, watched, seasons_seen, notes) = row
display_row = [
series,
seasons,
year,
self.bool_to_checkbox(present),
seasons_present,
self.bool_to_checkbox(complete),
self.bool_to_checkbox(watched),
seasons_seen,
notes
]
self.tree.insert('', 'end', iid=str(record_id), values=display_row)
def show_movies(self) -> None:
"""Display the movies table."""
self.load_movie_data()
def show_series(self) -> None:
"""Display the series table."""
self.load_series_data()
def add_entry(self) -> None:
"""Add a new entry to the current table."""
if self.current_table == 'movies':
run_query(
"INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', False, False, '')
)
self.load_movie_data()
elif self.current_table == 'series':
run_query(
"""INSERT INTO series
(series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
('', '', '', False, '', False, False, '', '')
)
self.load_series_data()
def delete_entry(self) -> None:
"""Delete the selected entry from the current table."""
selected_item = self.tree.selection()
if not selected_item:
messagebox.showwarning("No selection", "Please select a row to delete.")
return
row_id = selected_item[0]
run_query(f"DELETE FROM {self.current_table} WHERE id = ?", (row_id,))
if self.current_table == 'movies':
self.load_movie_data()
elif self.current_table == 'series':
self.load_series_data()
def on_row_select(self, event) -> None:
"""Handle the selection of a row in the Treeview."""
selected_item = self.tree.selection()
self.current_row_id = selected_item[0] if selected_item else None
if selected_item:
x, y, width, height = self.tree.bbox(self.current_row_id)
y_offset = y + height // 2
# Move buttons to align with the selected row
self.add_button.place(x=20, y=y_offset, anchor='center') # Adjust x as needed
self.delete_button.place(x=60, y=y_offset, anchor='center') # Adjust x as needed
def on_single_click(self, event) -> None:
"""Handle single click events for toggling boolean fields."""
region = self.tree.identify("region", event.x, event.y)
if region != "cell":
return
row_id = self.tree.identify_row(event.y)
column = self.tree.identify_column(event.x)
if not row_id or not column:
return
try:
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
except (IndexError, ValueError):
return
if column_name in self.BOOLEAN_COLUMNS.get(self.current_table, []):
current_value = self.tree.set(row_id, column_name)
new_value = not self.checkbox_to_bool(current_value)
self.tree.set(row_id, column_name, self.bool_to_checkbox(new_value))
row_values = self.tree.item(row_id)['values']
self.update_database(row_values)
def on_double_click(self, event) -> None:
"""Open an entry widget to edit the item on double-click."""
region = self.tree.identify("region", event.x, event.y)
if region != "cell":
return
column = self.tree.identify_column(event.x)
row_id = self.tree.identify_row(event.y)
if not row_id or not column:
return
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
# Create the entry widget to edit the selected cell
x, y, width, height = self.tree.bbox(row_id, column)
current_value = self.tree.set(row_id, column_name)
entry = tk.Entry(self.content, font=self.custom_font, relief='flat', borderwidth=0)
entry.place(x=x, y=y, width=width, height=height)
entry.insert(0, current_value)
entry.focus()
def on_focus_out(event):
new_value = entry.get()
# Update the Treeview with the new value
self.tree.set(row_id, column_name, new_value)
# Remove the entry widget
entry.destroy()
# Update the database
self.update_database_from_treeview()
entry.bind("<FocusOut>", on_focus_out)
entry.bind("<Return>", lambda event: on_focus_out(event)) # Update on Enter as well
def update_database(self, row_values: list) -> None:
"""Update the database with the modified row values."""
if self.current_table == 'movies':
query = """
UPDATE movies
SET movie = ?, year = ?, present = ?, watched = ?, notes = ?
WHERE id = ?
"""
parameters = (
row_values[0],
row_values[1],
self.checkbox_to_bool(row_values[2]),
self.checkbox_to_bool(row_values[3]),
row_values[4],
self.current_row_id
)
elif self.current_table == 'series':
query = """
UPDATE series
SET series = ?, seasons = ?, year = ?, present = ?, seasons_present = ?,
complete = ?, watched = ?, seasons_seen = ?, notes = ?
WHERE id = ?
"""
parameters = (
row_values[0],
row_values[1],
row_values[2],
self.checkbox_to_bool(row_values[3]),
row_values[4],
self.checkbox_to_bool(row_values[5]),
self.checkbox_to_bool(row_values[6]),
row_values[7],
row_values[8],
self.current_row_id
)
run_query(query, parameters)
def update_database_from_treeview(self):
"""Update database with values from the Treeview."""
for row_id in self.tree.get_children():
row_values = self.tree.item(row_id)['values']
self.current_row_id = row_id # Needed for update_database function
self.update_database(row_values)
def treeview_click_cursor(self, event) -> None:
"""Change the cursor to a hand when hovering over boolean columns."""
region = self.tree.identify("region", event.x, event.y)
if region == "cell":
column = self.tree.identify_column(event.x)
try:
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
cursor = "hand2" if column_name in self.BOOLEAN_COLUMNS.get(self.current_table, []) else ""
self.tree.configure(cursor=cursor)
except (IndexError, ValueError):
self.tree.configure(cursor="")
else:
self.tree.configure(cursor="")
@staticmethod
def bool_to_checkbox(value: bool) -> str:
"""Convert a boolean value to a checkbox symbol."""
return '☑' if value else '☐'
@staticmethod
def checkbox_to_bool(value: str) -> bool:
"""Convert a checkbox symbol to a boolean value."""
return value == '☑'
if __name__ == "__main__":
create_tables()
app = MediaTracker()
app.mainloop()
Explanation:
Button Positioning: The buttons are now initialized in the spacer bar, and they are dynamically placed based on the selection in the Treeview. The buttons align with the middle of the selected row using the on_row_select method.
Dynamic Button Movement: When a row is selected, the buttons move vertically to be adjacent to the selected row, providing an intuitive experience for adding or deleting entries related to the specific row.
No Initial Placement: The buttons are created with place() but are not positioned until a row selection triggers their movement. This ensures they stay relevant to user interaction. Adjustments can be made to the x positions for better alignment with the design.
Explanation
Event Binding: A click event is bound to both the Treeview and the main window to detect clicks anywhere in the application. This helps in clearing the selection when clicking outside of a row or the Treeview.
on_click Method: Handles mouse click events. It checks if a click happens outside a row in the Treeview and calls clear_selection.
clear_selection Method: This method removes any current selection from the Treeview and hides the buttons by using place_forget().
By integrating these methods and bindings, you can ensure that the row is deselected and the buttons are hidden unless there is an active selection within the Treeview.
import sys
import sqlite3
from pathlib import Path
import tkinter as tk
from tkinter import ttk, messagebox, font
MEDIA_DB = Path(__file__).parent / 'media.db'
if sys.platform.startswith('win'):
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print("Error setting DPI awareness:", e)
def run_query(query: str, parameters: tuple = ()) -> list:
"""Execute a SQL query and return the results if it's a SELECT statement."""
with sqlite3.connect(MEDIA_DB) as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
if query.strip().lower().startswith("select"):
return result.fetchall()
conn.commit()
def create_tables() -> None:
"""Create the movies and series tables in the database if they do not exist."""
run_query('''
CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
movie TEXT,
year TEXT,
present BOOLEAN,
watched BOOLEAN,
notes TEXT
);
''')
run_query('''
CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
series TEXT,
seasons TEXT,
year TEXT,
present BOOLEAN,
seasons_present TEXT,
complete BOOLEAN,
watched BOOLEAN,
seasons_seen TEXT,
notes TEXT
);
''')
class MediaTracker(tk.Tk):
"""A Tkinter application to track movies and series."""
BOOLEAN_COLUMNS = {
'movies': ['Present', 'Watched'],
'series': ['Present', 'Complete', 'Watched']
}
def __init__(self):
super().__init__()
self.configure(bg='white')
self.title("Movies and Series Tracker")
self.geometry("1200x600")
self.custom_font = self._get_custom_font()
self.current_table = None
self.current_row_id = None
self.tree = None
self.scrollbar = None
self._configure_style()
self._configure_scrollbar_style() # Configure scrollbar styles
self._configure_grid()
self._create_widgets()
self.show_movies()
def _get_custom_font(self) -> font.Font:
"""Retrieve the custom font, defaulting to Arial if Literata is unavailable."""
try:
return font.Font(family='Literata', size=12)
except:
return font.Font(family='Arial', size=12)
def _configure_style(self) -> None:
"""Configure the styles for Treeview and buttons."""
font_line_space = self.custom_font.metrics('linespace')
row_height = font_line_space + 4
style = ttk.Style()
style.theme_use("default")
style.layout(
'Custom.Treeview',
[('Custom.Treeview.treearea', {'sticky': 'nsew'})]
)
style.configure(
"Custom.Treeview",
font=self.custom_font,
rowheight=row_height,
borderwidth=0,
relief='flat',
highlightthickness=0,
background='white',
fieldbackground='white'
)
style.configure(
"Custom.Treeview.Heading",
font=(self.custom_font.cget("family"), self.custom_font.cget("size"), "bold"),
background='#F7F8FC',
relief='solid',
borderwidth=0,
anchor='center'
)
style.map(
"Custom.Treeview.Heading",
background=[('active', 'white')],
relief=[('active', 'solid')]
)
style.configure("Custom.TButton", font=self.custom_font)
def _configure_scrollbar_style(self) -> None:
"""Configure the style for Scrollbars."""
style = ttk.Style()
style.theme_use("default")
style.configure("Custom.Vertical.TScrollbar",
troughcolor='white',
background='#c6c6c6',
bordercolor='white',
arrowcolor='white',
borderwidth=0,
relief='flat')
style.map("Custom.Vertical.TScrollbar",
background=[('active', '#9b9b9b'), ('pressed', '#8b8b8bff')])
style.layout('Custom.Vertical.TScrollbar',
[('Vertical.Scrollbar.trough',
{'children': [('Vertical.Scrollbar.thumb', {'expand': '1',
'sticky': 'nswe'})],
'sticky': 'ns'})])
def _configure_grid(self) -> None:
"""Configure the grid layout for the main window."""
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(2, weight=1)
def _create_widgets(self) -> None:
"""Create and layout all the widgets in the application."""
self.header_canvas = tk.Canvas(self, bg='white', highlightthickness=0, height=100)
self.header_canvas.grid(row=0, column=1, columnspan=3, sticky='ew')
self.header_canvas.grid_propagate(False)
self.update_header("Movies")
sidebar = tk.Frame(self, width=150, bg='#F7F8FC')
sidebar.grid(row=0, column=0, rowspan=2, sticky='ns')
sidebar.grid_propagate(False)
self.sidebar = sidebar
spacer = tk.Frame(self, width=100, bg='white')
spacer.grid(row=1, column=1, sticky='ns')
spacer.grid_propagate(False)
self.spacer = spacer
content = tk.Frame(self, bg='white')
content.grid(row=1, column=2, sticky='nsew')
self.content = content
self._create_buttons() # Create buttons in spacer
self._create_sidebar_labels()
self.bind_events() # Bind events for managing selection and clicking outside the treeview
def update_header(self, text: str) -> None:
"""Update the header with the given text."""
self.header_canvas.delete("all")
small_font = font.Font(family=self.custom_font.actual('family'), size=10)
self.header_canvas.create_text(
10, 10,
anchor='nw',
text="Data >",
fill='#999999',
font=small_font
)
self.header_canvas.create_text(
80, 10,
anchor='nw',
text=text,
fill='black',
font=small_font
)
def _create_sidebar_labels(self) -> None:
"""Create labels for the sidebar to switch between Movies and Series."""
self.create_sidebar_label("Movies", self.show_movies, pady=100)
self.create_sidebar_label("Series", self.show_series, pady=0)
def create_sidebar_label(self, text: str, command, pady=0) -> None:
"""Create a clickable label in the sidebar."""
label = tk.Label(
self.sidebar,
text=text,
bg='#F7F8FC',
font=self.custom_font,
cursor="hand2",
anchor='w',
padx=50,
pady=0
)
label.pack(pady=(pady, 1), fill='x')
label.bind("<Enter>", lambda e: label.config(bg='#EAEDEF'))
label.bind("<Leave>", lambda e: label.config(bg='#F7F8FC'))
label.bind("<Button-1>", lambda e: command())
def _create_buttons(self) -> None:
"""Create add and delete buttons within the spacer."""
style = ttk.Style()
style.configure("Square.TButton",
font=('Arial', 14),
padding=(1, 1),
width=2,
background='white',
borderwidth=0,
relief='flat')
style.map("Square.TButton",
background=[('active', '#EAEDEF')])
# Initialize buttons but do not pack them initially
self.add_button = ttk.Button(
self.spacer,
text="+",
command=self.add_entry,
style="Square.TButton"
)
self.delete_button = ttk.Button(
self.spacer,
text="-",
command=self.delete_entry,
style="Square.TButton"
)
def clear_content(self) -> None:
"""Clear the content frame by destroying the tree and scrollbar if they exist."""
for widget in [self.tree, self.scrollbar]:
if widget:
widget.destroy()
self.tree = None
self.scrollbar = None
def setup_treeview(self, columns: list, headings: list) -> None:
"""Set up the Treeview widget with specified columns and headings."""
self.tree = ttk.Treeview(
self.content,
columns=columns,
show='headings',
selectmode='browse',
style="Custom.Treeview"
)
for col, head in zip(columns, headings):
self.tree.heading(col, text=head, anchor='center')
anchor = 'w' if head.lower() == 'notes' else 'center'
width = 300 if head.lower() == 'notes' else 100 if head in self.BOOLEAN_COLUMNS.get(self.current_table, []) else 150
self.tree.column(col, width=width, anchor=anchor)
self.scrollbar = ttk.Scrollbar(
self.content,
orient="vertical",
command=self.tree.yview,
style="Custom.Vertical.TScrollbar" # Use the custom style
)
self.tree.configure(yscrollcommand=self.scrollbar.set)
self.scrollbar.pack(side='right', fill='y')
self.tree.pack(fill='both', expand=True)
self.tree.bind('<<TreeviewSelect>>', self.on_row_select)
self.tree.bind('<Button-1>', self.on_single_click)
self.tree.bind("<Double-Button-1>", self.on_double_click) # Bind double-click event
self.tree.bind("<Motion>", self.treeview_click_cursor)
def load_movie_data(self) -> None:
"""Load and display movie data in the Treeview."""
self.clear_content()
columns = ["Movie", "Year", "Present", "Watched", "Notes"]
self.setup_treeview(columns, columns)
self.current_table = 'movies'
self.update_header("Movies")
for row in run_query('SELECT * FROM movies'):
record_id, movie, year, present, watched, notes = row
display_row = [
movie,
year,
self.bool_to_checkbox(present),
self.bool_to_checkbox(watched),
notes
]
self.tree.insert('', 'end', iid=str(record_id), values=display_row)
def load_series_data(self) -> None:
"""Load and display series data in the Treeview."""
self.clear_content()
columns = ["Series", "Seasons", "Year", "Present",
"Seasons Present", "Complete", "Watched",
"Seasons Seen", "Notes"]
self.setup_treeview(columns, columns)
self.current_table = 'series'
self.update_header("Series")
for row in run_query('SELECT * FROM series'):
(record_id, series, seasons, year, present, seasons_present,
complete, watched, seasons_seen, notes) = row
display_row = [
series,
seasons,
year,
self.bool_to_checkbox(present),
seasons_present,
self.bool_to_checkbox(complete),
self.bool_to_checkbox(watched),
seasons_seen,
notes
]
self.tree.insert('', 'end', iid=str(record_id), values=display_row)
def show_movies(self) -> None:
"""Display the movies table."""
self.load_movie_data()
def show_series(self) -> None:
"""Display the series table."""
self.load_series_data()
def add_entry(self) -> None:
"""Add a new entry to the current table."""
if self.current_table == 'movies':
run_query(
"INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', False, False, '')
)
self.load_movie_data()
elif self.current_table == 'series':
run_query(
"""INSERT INTO series
(series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
('', '', '', False, '', False, False, '', '')
)
self.load_series_data()
def delete_entry(self) -> None:
"""Delete the selected entry from the current table with confirmation."""
selected_item = self.tree.selection()
if not selected_item:
messagebox.showwarning("No selection", "Please select a row to delete.")
return
# Confirmation dialog
confirm = messagebox.askokcancel(
"Confirm Deletion",
"This action cannot be undone.\nDo you want to delete the selected entry?",
icon='warning'
)
if confirm:
row_id = selected_item[0]
run_query(f"DELETE FROM {self.current_table} WHERE id = ?", (row_id,))
if self.current_table == 'movies':
self.load_movie_data()
elif self.current_table == 'series':
self.load_series_data()
def on_row_select(self, event) -> None:
"""Handle the selection of a row in the Treeview."""
selected_item = self.tree.selection()
self.current_row_id = selected_item[0] if selected_item else None
if selected_item:
x, y, width, height = self.tree.bbox(self.current_row_id)
y_offset = y + height // 2
# Move buttons to align with the selected row, flipping their positions
self.delete_button.place(x=20, y=y_offset, anchor='center') # Minus button on the left
self.add_button.place(x=60, y=y_offset, anchor='center') # Plus button on the right
else:
# Hide buttons if no row is selected
self.clear_selection()
def on_single_click(self, event) -> None:
"""Handle single click events for toggling boolean fields."""
region = self.tree.identify("region", event.x, event.y)
if region != "cell":
return
row_id = self.tree.identify_row(event.y)
column = self.tree.identify_column(event.x)
if not row_id or not column:
return
try:
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
except (IndexError, ValueError):
return
if column_name in self.BOOLEAN_COLUMNS.get(self.current_table, []):
current_value = self.tree.set(row_id, column_name)
new_value = not self.checkbox_to_bool(current_value)
self.tree.set(row_id, column_name, self.bool_to_checkbox(new_value))
row_values = self.tree.item(row_id)['values']
self.update_database(row_values)
def on_double_click(self, event) -> None:
"""Open an entry widget to edit the item on double-click."""
region = self.tree.identify("region", event.x, event.y)
if region != "cell":
return
column = self.tree.identify_column(event.x)
row_id = self.tree.identify_row(event.y)
if not row_id or not column:
return
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
# Create the entry widget to edit the selected cell
x, y, width, height = self.tree.bbox(row_id, column)
current_value = self.tree.set(row_id, column_name)
entry = tk.Entry(self.content, font=self.custom_font, relief='flat', borderwidth=0)
entry.place(x=x, y=y, width=width, height=height)
entry.insert(0, current_value)
entry.focus()
def on_focus_out(event):
new_value = entry.get()
# Update the Treeview with the new value
self.tree.set(row_id, column_name, new_value)
# Remove the entry widget
entry.destroy()
# Update the database
self.update_database_from_treeview()
entry.bind("<FocusOut>", on_focus_out)
entry.bind("<Return>", lambda event: on_focus_out(event)) # Update on Enter as well
def update_database(self, row_values: list) -> None:
"""Update the database with the modified row values."""
if self.current_table == 'movies':
query = """
UPDATE movies
SET movie = ?, year = ?, present = ?, watched = ?, notes = ?
WHERE id = ?
"""
parameters = (
row_values[0],
row_values[1],
self.checkbox_to_bool(row_values[2]),
self.checkbox_to_bool(row_values[3]),
row_values[4],
self.current_row_id
)
elif self.current_table == 'series':
query = """
UPDATE series
SET series = ?, seasons = ?, year = ?, present = ?, seasons_present = ?,
complete = ?, watched = ?, seasons_seen = ?, notes = ?
WHERE id = ?
"""
parameters = (
row_values[0],
row_values[1],
row_values[2],
self.checkbox_to_bool(row_values[3]),
row_values[4],
self.checkbox_to_bool(row_values[5]),
self.checkbox_to_bool(row_values[6]),
row_values[7],
row_values[8],
self.current_row_id
)
run_query(query, parameters)
def update_database_from_treeview(self):
"""Update database with values from the Treeview."""
for row_id in self.tree.get_children():
row_values = self.tree.item(row_id)['values']
self.current_row_id = row_id # Needed for update_database function
self.update_database(row_values)
def treeview_click_cursor(self, event) -> None:
"""Change the cursor to a hand when hovering over boolean columns."""
region = self.tree.identify("region", event.x, event.y)
if region == "cell":
column = self.tree.identify_column(event.x)
try:
col_index = int(column.replace('#', '')) - 1
column_name = self.tree['columns'][col_index]
cursor = "hand2" if column_name in self.BOOLEAN_COLUMNS.get(self.current_table, []) else ""
self.tree.configure(cursor=cursor)
except (IndexError, ValueError):
self.tree.configure(cursor="")
else:
self.tree.configure(cursor="")
def clear_selection(self):
"""Clears the treeview selection and hides the buttons."""
# Deselect any selected items
self.tree.selection_remove(self.tree.selection())
self.current_row_id = None
# Hide buttons
self.delete_button.place_forget()
self.add_button.place_forget()
def bind_events(self):
"""Bind necessary events for the treeview."""
# Bind to clicks on the treeview but outside of a row to clear selection
self.tree.bind("<Button-1>", self.on_click, add="+")
# Bind to any click on the window to potentially clear selection
self.bind("<Button-1>", self.on_click, add="+")
def on_click(self, event):
"""Handle clicks to manage selection and button visibility."""
widget_clicked = event.widget
# Check if the click is outside of the Treeview
if widget_clicked != self.tree:
self.clear_selection()
else:
row_id = self.tree.identify_row(event.y)
if not row_id:
self.clear_selection()
@staticmethod
def bool_to_checkbox(value: bool) -> str:
"""Convert a boolean value to a checkbox symbol."""
return '☑' if value else '☐'
@staticmethod
def checkbox_to_bool(value: str) -> bool:
"""Convert a checkbox symbol to a boolean value."""
return value == '☑'
if __name__ == "__main__":
create_tables()
app = MediaTracker()
app.mainloop()
Key Enhancements:
Unselect Row and Hide Buttons: Clicking outside the Treeview or on a non-row area within it will now deselect the current selection and hide the plus and minus buttons.
Event Binding: The bind_events method binds the <Button-1> event to both the Treeview and the application window. This captures all click events to determine when the selection should be cleared.
clear_selection Method: This method centralizes logic to clear any selection and hide the buttons when necessary, streamlining the interface behavior.
These changes create a more intuitive user experience by ensuring the buttons only appear when a specific row is selected, and are hidden when the user interacts with other parts of the application.