Currently when i open the dropdown menu and then click outside the dropdown menu the menu does not close. I want the menu to close. 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
code
Assistant
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)
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))
var = tk.StringVar(value=current_type)
dropdown_button = tk.Label(
frame,
textvariable=var,
bg=self.colors["background"],
fg=self.colors["header_info"],
font=self.fonts["menu"],
cursor="hand2",
width=10,
anchor='w'
)
dropdown_button.pack(side=tk.RIGHT)
def create_dropdown(header, var, button):
def show_dropdown(event):
x = button.winfo_rootx()
y = button.winfo_rooty() + button.winfo_height()
dropdown = tk.Toplevel(self.datatype_popup) # Ensure dropdown is child of datatype_popup
dropdown.overrideredirect(True)
dropdown.geometry(f"+{x}+{y}")
# Create a border frame
border_frame = tk.Frame(dropdown, bg=self.colors["frame_border"])
border_frame.pack(padx=0, pady=0, expand=True, fill=tk.BOTH)
# Create an inner frame for the options
inner_frame = tk.Frame(border_frame, bg=self.colors["background"])
inner_frame.pack(padx=1, pady=1, expand=True, fill=tk.BOTH)
for option in self.DATA_TYPE_OPTIONS:
option_label = tk.Label(
inner_frame,
text=option,
bg=self.colors["background"],
fg=self.colors["header_info"],
font=self.fonts["menu"],
anchor='w',
width=10
)
option_label.pack(fill=tk.X)
option_label.bind("<Enter>", lambda e: e.widget.config(bg=self.colors["button_selected"]))
option_label.bind("<Leave>", lambda e: e.widget.config(bg=self.colors["background"]))
option_label.bind("<Button-1>", lambda e, opt=option: (var.set(opt), dropdown.destroy()))
# Use the <FocusOut> event to close the dropdown
dropdown.bind("<FocusOut>", lambda e: dropdown.destroy())
button.bind("<Button-1>", show_dropdown)
create_dropdown(header, var, dropdown_button)
self.datatype_vars[header] = var
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())
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}")
# Define the helper function to check if a widget is a descendant
def is_descendant(widget, ancestor):
while widget:
if widget == ancestor:
return True
widget = widget.master
return False
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):
# Don't close the popup if the click was inside the main popup or its descendants
if not is_descendant(event.widget, 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())
# Remove the binding to <FocusOut> on the main popup
# self.datatype_popup.bind("<FocusOut>", close_popup)
self.datatype_popup.bind("<Escape>", close_popup)
self.datatype_popup.focus_force()
The issue you're experiencing arises because the click event that should close the dropdown menu is being handled by the root window's <Button-1> binding, which interferes with the dropdown's own event handling. Specifically, when you click outside the dropdown, the root's binding closes the main popup (datatype_popup) instead of the dropdown.
Here's how you can fix it:
Keep Track of the Dropdown: Store a reference to the dropdown menu so that you can check if the click event occurred inside it.
Modify the is_descendant Function: Update the is_descendant function to accept a list of ancestors, allowing you to check if a widget is a descendant of any widget in that list.
Update the Click Outside Handler: Modify the click_outside_popup function to include the dropdown in its ancestor check. This ensures that clicks inside the dropdown won't close the main popup.
Manage the Dropdown's Lifecycle: Ensure that when the dropdown is destroyed, you reset the reference to it (self.dropdown = None) so that future checks are accurate.
Properly Unbind Events: When destroying the dropdown, make sure to unbind any event bindings that were specific to it.
Here's the updated code with these changes applied:
Tracking the Dropdown: We added an attribute self.dropdown to keep track of the currently open dropdown menu.
Modified is_descendant: The function now accepts a list of ancestors, allowing us to check if a widget is a descendant of any widget in that list.
Updated click_outside_popup: This function now includes the dropdown in its ancestor check. If a click occurs outside both the datatype_popup and the dropdown, it closes the popup.
Managing the Dropdown's Lifecycle: When the dropdown is destroyed, we reset self.dropdown to None.
Event Binding for the Dropdown: We bind a new function click_outside_dropdown to handle clicks outside the dropdown, which closes it appropriately.
By making these changes, clicks outside the dropdown menu will now close it, and clicks outside the main popup will close the popup without interfering with the dropdown's event handling.