Modify the code so that the datatypes option menu uses not a box but it should use the same window like the datatype menu. Python 3.12 Code: def show_datatype_dialog(self) -> None:
"""Show custom popup window for changing column data types."""
table_name = self.app.current_table_name
if not table_name:
messagebox.showwarning("No Table Selected", "Please select a table to change datatypes.")
return
To modify your show_datatype_dialog method so that the data type selection uses a custom menu (like your existing datatype menu) instead of the standard tk.OptionMenu, you can replace the OptionMenu widgets with custom popup menus built with tk.Toplevel windows and tk.Labels. This approach allows you to style the menus consistently and provides more control over their appearance and behavior.
Below is the modified code with detailed explanations:
python
def show_datatype_dialog(self) -> None:
"""Show custom popup window for changing column data types using custom menus."""
table_name = self.app.current_table_name
if not table_name:
messagebox.showwarning("No Table Selected", "Please select a table to change datatypes.")
return
current_headers = self.app.current_sheet.headers() if self.app.current_sheet else []
self.app.data_manager.headers[table_name] = current_headers
self.data_types = self.app.data_manager.tables_data[table_name].get("data_types", []).copy()
while len(self.data_types) < len(current_headers):
self.data_types.append('string')
if hasattr(self, 'datatype_popup') and self.datatype_popup.winfo_exists():
self.datatype_popup.destroy()
self.datatype_popup = tk.Toplevel(self.root)
self.datatype_popup.overrideredirect(True)
border_frame = tk.Frame(self.datatype_popup, bg=self.colors["frame_border"])
border_frame.pack(padx=0, pady=0, expand=True, fill=tk.BOTH)
content_frame = tk.Frame(border_frame, bg=self.colors["background"])
content_frame.pack(padx=1, pady=1, expand=True, fill=tk.BOTH)
inner_frame = tk.Frame(content_frame, bg=self.colors["background"])
inner_frame.pack(padx=10, pady=10, expand=True, fill=tk.BOTH)
self.datatype_vars = {}
for header_index, header in enumerate(current_headers):
current_type = self.data_types[header_index]
frame = tk.Frame(inner_frame, bg=self.colors["background"])
frame.pack(fill=tk.X, pady=0)
# Create label for the header
header_label = tk.Label(
frame,
text=f"{header}:",
bg=self.colors["background"],
fg=self.colors["text"],
font=self.fonts["menu"]
)
header_label.pack(side=tk.LEFT, padx=(0, 10))
# Variable to hold the selected data type
var = tk.StringVar(value=current_type)
# Create a label that displays the current data type and acts as a button
data_type_container = tk.Frame(frame, bg=self.colors["background"], cursor="hand2")
data_type_container.pack(side=tk.RIGHT)
data_type_label = tk.Label(
data_type_container,
text=var.get(),
bg=self.colors["background"],
fg=self.colors["header_info"],
font=self.fonts["menu"],
cursor="hand2"
)
data_type_label.pack()
# Function to show custom menu when data_type_label is clicked
def make_show_type_menu(event, var=var, data_type_label=data_type_label):
# Destroy any existing type menu popup
if hasattr(self, 'type_menu_popup') and self.type_menu_popup.winfo_exists():
self.type_menu_popup.destroy()
# Function to create and display the custom type menu
def show_type_menu():
self.type_menu_popup = tk.Toplevel(self.root)
self.type_menu_popup.overrideredirect(True)
self.type_menu_popup.transient(self.root)
type_frame = tk.Frame(self.type_menu_popup, bg=self.colors["background"])
type_frame.pack()
# Create labels for each data type option
for option in self.DATA_TYPE_OPTIONS:
option_label = tk.Label(
type_frame,
text=option,
bg=self.colors["background"],
fg=self.colors["text"],
font=self.fonts["menu"],
cursor="hand2"
)
option_label.pack(fill=tk.X, padx=10, pady=5)
# Function to handle option selection
def select_option(event, option=option):
var.set(option)
data_type_label.config(text=option)
self.type_menu_popup.destroy()
option_label.bind("<Button-1>", select_option)
# Position the popup menu just below the data_type_label
self.type_menu_popup.update_idletasks()
popup_width = self.type_menu_popup.winfo_width()
popup_height = self.type_menu_popup.winfo_height()
widget_x = event.widget.winfo_rootx()
widget_y = event.widget.winfo_rooty() + event.widget.winfo_height()
# Adjust position if the popup goes beyond screen boundaries
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
if widget_x + popup_width > screen_width:
widget_x = screen_width - popup_width
if widget_y + popup_height > screen_height:
widget_y = widget_y - popup_height - event.widget.winfo_height()
self.type_menu_popup.geometry(f"+{widget_x}+{widget_y}")
# Close the popup when clicking outside of it
def close_type_menu(event):
if not str(event.widget).startswith(str(self.type_menu_popup)):
if hasattr(self, 'type_menu_popup') and self.type_menu_popup.winfo_exists():
self.type_menu_popup.destroy()
self.root.unbind("<Button-1>", close_type_menu)
self.root.bind("<Button-1>", close_type_menu)
show_type_menu()
# Bind the click event to show the custom type menu
data_type_container.bind("<Button-1>", make_show_type_menu)
data_type_label.bind("<Button-1>", make_show_type_menu)
self.datatype_vars[header] = var
# Separator and apply button (unchanged)
separator = tk.Frame(inner_frame, bg=self.colors["separator_menu"], height=1)
separator.pack(fill=tk.X, pady=(5, 5))
apply_container = tk.Frame(
inner_frame,
bg=self.colors["background"],
cursor="hand2"
)
apply_container.pack(fill=tk.X, pady=(5, 0))
apply_label = tk.Label(
apply_container,
text="Apply Changes",
bg=self.colors["background"],
fg=self.colors["text"],
font=self.fonts["menu"],
cursor="hand2"
)
apply_label.pack(expand=True, fill=tk.BOTH, pady=0)
def on_hover_enter(event):
apply_container.config(bg=self.colors["button_selected"])
apply_label.config(bg=self.colors["button_selected"])
def on_hover_leave(event):
apply_container.config(bg=self.colors["background"])
apply_label.config(bg=self.colors["background"])
apply_container.bind("<Enter>", on_hover_enter)
apply_container.bind("<Leave>", on_hover_leave)
apply_label.bind("<Enter>", on_hover_enter)
apply_label.bind("<Leave>", on_hover_leave)
apply_container.bind("<Button-1>", lambda e: self._apply_changes())
apply_label.bind("<Button-1>", lambda e: self._apply_changes())
# Position the main datatype_popup window
self.datatype_popup.update_idletasks()
popup_width = self.datatype_popup.winfo_width()
popup_height = self.datatype_popup.winfo_height()
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
menu_x = self.root.winfo_pointerx()
menu_y = self.root.winfo_pointery()
padding = 10
if menu_x + popup_width > screen_width - padding:
menu_x = screen_width - popup_width - padding
if menu_y + popup_height > screen_height - padding:
menu_y = screen_height - popup_height - padding
menu_x = max(padding, menu_x)
menu_y = max(padding, menu_y)
self.datatype_popup.geometry(f"+{menu_x}+{menu_y}")
# Function to close the main popup when clicking outside
def close_popup(event=None):
if self.datatype_popup.winfo_exists():
self.datatype_popup.destroy()
self.root.unbind("<Button-1>", self.click_outside_popup)
self.root.unbind("<Configure>", self.window_resized)
def click_outside_popup(event):
if not str(event.widget).startswith(str(self.datatype_popup)):
close_popup()
self.click_outside_popup = self.root.bind("<Button-1>", click_outside_popup)
self.window_resized = self.root.bind("<Configure>", lambda e: close_popup())
self.datatype_popup.bind("<FocusOut>", close_popup)
self.datatype_popup.bind("<Escape>", close_popup)
self.datatype_popup.focus_force()
Explanation of Changes:
Removed OptionMenu: The tk.OptionMenu widget is removed. Instead, a tk.Label is used to display the current data type.
Added data_type_container and data_type_label: These widgets display the current data type and act as a clickable area to open the custom menu.
Created make_show_type_menu Function: An inner function make_show_type_menu is defined to handle the click event and show the custom type menu.
Implemented Custom Type Menu:
A new tk.Toplevel window (self.type_menu_popup) is created to serve as the custom menu.
Labels for each data type option are added to this popup.
Clicking on an option updates the var (the StringVar holding the selected data type) and updates the data_type_label.
Positioning and Closing the Popup:
The custom menu is positioned just below the data_type_label.
Event bindings are added to close the popup when clicking outside of it or selecting an option.
Event Bindings and Variable Scoping:
Default arguments are used in inner functions to capture the current values of variables (var, data_type_label, and option), ensuring that the correct values are used in closures.
Event bindings are carefully managed to prevent multiple bindings and ensure that popups are destroyed appropriately.
Consistency with Existing Menus:
The styles (bg, fg, font, etc.) in the custom menu are set to match those of the existing datatype menu, ensuring a consistent look and feel.
Notes:
Ensure that the self.DATA_TYPE_OPTIONS list contains the data types you want to offer.
Adjust the styling (colors, fonts) as needed to match your application's theme.
The self._apply_changes() method is assumed to handle applying the selected data types to the table columns.
By making these changes, the data type selection in your show_datatype_dialog will now use custom menus that match the style of your existing datatype menu, providing a consistent and visually integrated user interface.