def thought_function(main_text, hoverable_words):
thoughts = {}
for word in hoverable_words:
thoughts[word] = generate_garbled_lorem_ipsum()
return thoughts
class HoverableText(customtkinter.CTkTextbox):
def init(self, *args, thoughts=None, hoverable_words=None, **kwargs):
super().init(*args, **kwargs)
self.thoughts = thoughts or {}
self.hoverable_words = hoverable_words or []
self.configure(wrap='word', height=50, width=250)
self.tag_config("hoverable", foreground="blue", underline=1)
self.bind("", self.on_enter)
self.bind("", self.on_leave)
self.current_popup = None # Track the current popup
code
def on_enter(self, event):
self.configure(cursor="hand2")
# Calculate the position of the cursor when it first hovers over the element
x, y = event.x_root, event.y_root
# Create a new popup at the cursor position
self.current_popup = create_popup(x, y, self.winfo_toplevel(), "Hover Text")
logging.info(f"{Fore.GREEN}Popup created for element{Style.RESET_ALL}")
def on_leave(self, event):
self.configure(cursor="")
if self.current_popup and self.current_popup.winfo_exists():
self.current_popup.destroy()
logging.info(f"{Fore.RED}Popup destroyed{Style.RESET_ALL}")
self.current_popup = None
def calculate_popup_position(x, y, popup_width, popup_height):
# Calculate the position of the popup at the cursor position
popup_x = x - popup_width // 2 # Center the popup horizontally
popup_y = y - popup_height + 150 # Position the popup above the cursor with an offset
return popup_x, popup_y
text_widget = HoverableText(root, thoughts=thoughts, hoverable_words=hoverable_words)
text_widget.pack(pady=20)
text_widget.insert("1.0", main_text)
text_widget.configure(state="disabled")
for word in hoverable_words:
start = "1.0"
while True:
start = text_widget.search(word, start, stopindex="end")
if not start:
break
end = f"{start}+{len(word)}c"
text_widget.tag_add("hoverable", start, end)
start = end
# Start the background task to clean up undestroyed popups
root.after(10000, cleanup_popups, root)
def cleanup_popups(root):
for widget in root.winfo_children():
if isinstance(widget, customtkinter.CTkToplevel) and widget.winfo_exists():
widget.destroy()
logging.info(f"{Fore.YELLOW}Undestroyed popup cleaned up{Style.RESET_ALL}")
# Schedule the cleanup task to run again after 10 seconds
root.after(7000, cleanup_popups, root)
if name == "main":
root = customtkinter.CTk()
root.geometry("300x200")
setup_hoverable_element(root)
root.mainloop()
Assistant
Nods
User
the documentation for the fairy_popup.py script
Fairy Popup Documentation
Overview
The fairy_popup.py script is an interactive GUI application that simulates a thought process by displaying popup boxes containing "thoughts" (randomly generated text) when specific words are hovered over. The script uses the customtkinter library for GUI components and colorama for colored logging. The main components of the script include the ThoughtManager, PopupBox, and HoverableText classes.
Classes
ThoughtManager
The ThoughtManager class is responsible for managing the main text, determining which words are hoverable, and assigning thoughts to those words. It also creates instances of PopupBox for each hoverable word.
Methods
__init__(): Initializes the ThoughtManager instance by determining the main text, hoverable words, and associated thoughts. It also creates PopupBox instances for each hoverable word.
main_text_determiner(): Returns the main text to be displayed.
determiner_function(main_text): Determines which words in the main text are hoverable.
thought_function(main_text, hoverable_words): Generates thoughts for each hoverable word.
create_popup_boxes(): Creates PopupBox instances for each hoverable word and stores them in a dictionary.
PopupBox
The PopupBox class encapsulates the logic for creating and managing popups. Each PopupBox instance contains the word and associated thought.
Methods
__init__(word, thought): Initializes the PopupBox instance with the word and associated thought.
create_popup(x, y, root): Creates a popup at the specified position (x, y) relative to the root window. The popup contains the word and associated thought.
HoverableText
The HoverableText class extends customtkinter.CTkTextbox and is responsible for displaying the main text with hoverable words. It creates popups when a word is hovered over.
Methods
Assistant
Nods
User
my bad there is new ver to the code. see this first:
fairy_popup.py
import customtkinter
from text_generator import generate_garbled_lorem_ipsum
import random
import logging
from colorama import Fore, Style, init
def main_text_determiner(self):
return "This is the hover text. It can be dynamically set."
def determiner_function(self, main_text):
return ["hover", "can"]
def thought_function(self, main_text, hoverable_words):
thoughts = {}
for word in hoverable_words:
thoughts[word] = generate_garbled_lorem_ipsum()
return thoughts
class HoverableText(customtkinter.CTkTextbox):
def init(self, thought_manager, *args, **kwargs):
super().init(*args, **kwargs)
self.thought_manager = thought_manager
self.configure(wrap='word', height=50, width=250)
self.tag_config("hoverable", foreground="blue", underline=1)
self.bind("", self.on_enter)
self.bind("", self.on_leave)
self.current_popup = None # Track the current popup
code
def on_enter(self, event):
self.configure(cursor="hand2")
# Calculate the position of the cursor when it first hovers over the element
x, y = event.x_root, event.y_root
# Create a new popup at the cursor position
self.current_popup = create_popup(x, y, self.winfo_toplevel(), "Hover Text")
logging.info(f"{Fore.GREEN}Popup created for element{Style.RESET_ALL}")
def on_leave(self, event):
self.configure(cursor="")
if self.current_popup and self.current_popup.winfo_exists():
self.current_popup.destroy()
logging.info(f"{Fore.RED}Popup destroyed{Style.RESET_ALL}")
self.current_popup = None
Assistant
Nods
User
i need u to set the ctkinter screen to dark theme. i need the popup box to also follow the dark theme. i also need for frame that hold label in the box, well, i need its background color to go transparent. then, i notice the popup box always appear on left from cursor, with this gap around 10px i think. i dont want there any gap, and i want the box to be on right of the cursor instead.
Assistant
To accomplish the updates you've requested, you need to make modifications to the fairy_popup.py script. Here's how you can achieve each of your requirements:
Set the CTkinter screen to a dark theme: You can configure the application's theme by setting the appearance mode to "dark" at the start of the program.
Make the popup box follow the dark theme: This usually happens automatically if the appearance mode is set properly, but ensure that any specific widget configurations do not override the theme settings.
Set the frame that holds the label in the popup to have a transparent background: You need to set the frame's background color to be transparent. This can sometimes be achieved by setting the frame's color to match the parent widget or specifying a color mode that supports transparency.
Position the popup box to the right of the cursor without any gap: Adjust the calculate_popup_position function to change the logic for positioning the popup relative to the cursor.
Here’s an updated version of your script with the necessary changes:
python
User
i receive this error:
Traceback (most recent call last):
File "c:\Users\Name\Downloads\xz\fairy_popup\fairy_popup.py", line 64, in create_popup
content_frame = customtkinter.CTkFrame(popup, corner_radius=10, fg_color=("transparent",))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\customtkinter\windows\widgets\ctk_frame.py", line 48, in init
self._fg_color = self._check_color_type(fg_color, transparency=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\customtkinter\windows\widgets\appearance_mode\appearance_mode_base_class.py", line 53, in _check_color_type
raise ValueError(f"transparency is not allowed in tuple color {color}, use 'transparent'")
ValueError: transparency is not allowed in tuple color ('transparent',), use 'transparent'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python312\Lib\tkinter_init_.py", line 1948, in call
return self.func(*args)
^^^^^^^^^^^^^^^^
File "c:\Users\Name\Downloads\xz\fairy_popup\fairy_popup.py", line 49, in on_enter
self.current_popup = create_popup(x, y, self.winfo_toplevel(), "Hover Text")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Name\Downloads\xz\fairy_popup\fairy_popup.py", line 74, in create_popup
logging.error(f"{Fore.PURPLE}Error in create_popup: {e}{Style.RESET_ALL}")
^^^^^^^^^^^
AttributeError: 'AnsiFore' object has no attribute 'PURPLE'
Assistant
It looks like there are a couple of errors in the code:
Transparency Issue: The error message indicates that when setting transparency for the color in customtkinter, you should use the string 'transparent' instead of a tuple containing 'transparent'.
Logging Color Error: The use of Fore.PURPLE is causing an error because colorama.Fore does not have a PURPLE attribute. You can use Fore.MAGENTA as an alternative since it commonly represents a purple color in console outputs.
Here are the updates to fix these issues:
Updated Code
python
User
it work. but the positioning dont work if screen is currently in minimized mode. u know, small screen ver. i think it need totake screen size change to calculation. you know, maybe divide it or smoething.
Assistant
To handle different screen sizes, including when the screen is resized or minimized, you need to take the screen's current size into account when calculating the popup's position. This involves dynamically adjusting the position based on the available screen space.
To achieve this, we'll modify calculate_popup_position to ensure the popup is displayed within the visible screen area, even when the window size is reduced. Here's how you can adjust the code:
Updated calculate_popup_position Function
python
def calculate_popup_position(x, y, popup_width, popup_height, root):
# Get the screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# Calculate the new popup position
popup_x = x + 1 # Position the popup immediately to the right of the cursor
popup_y = y - popup_height // 2 # Center the popup vertically relative to the cursor
# Ensure the popup does not go out of the screen bounds
if popup_x + popup_width > screen_width:
popup_x = screen_width - popup_width # Align to the right edge
if popup_y + popup_height > screen_height:
popup_y = screen_height - popup_height # Align to the bottom edge
if popup_y < 0:
popup_y = 0 # Align to the top edge
return popup_x, popup_y
Integration with Create Popup
Modify the call to calculate_popup_position when creating the popup in the create_popup function:
python
popup_x, popup_y = calculate_popup_position(x, y, popup_width, popup_height, root)
Full Context
Here's the relevant part added to your existing code:
python
User
there is gap distance if the screen is currently minimzed, but this will do for now. it is better. well done.
Assistant
I'm glad to hear that the solution is an improvement for your needs. Adjusting for minimized screens can be tricky due to varying behavior across different operating systems and window managers. If you have any more questions or need further assistance in the future, feel free to reach out. Happy coding!
User
i want the cursor to be able to hover over the box when the cursor is over the box. in this state, have the box not disappear. can you do it?
Assistant
To keep the popup box visible when hovering over it, you'll need to modify how the hover event handlers work. Specifically, you'll want to make sure that the popup is not destroyed when the cursor enters it. This can be achieved by adding bind events to the popup itself and modifying the HoverableText class's behavior.
Here's how you can adjust the code to achieve this behavior:
__init__(thought_manager, *args, **kwargs): Initializes the HoverableText instance with a ThoughtManager instance. It configures the textbox and binds event handlers for hovering.
on_enter(event): Handles the event when the cursor enters the textbox. It creates a popup at the cursor position for the hovered word.
on_leave(event): Handles the event when the cursor leaves the textbox. It destroys the current popup if it exists.
Functions
calculate_popup_position(x, y, popup_width, popup_height)
Calculates the position of the popup relative to the cursor position. The popup is centered horizontally and positioned above the cursor with an offset.
Parameters
x: The x-coordinate of the cursor.
y: The y-coordinate of the cursor.
popup_width: The width of the popup.
popup_height: The height of the popup.
Returns
A tuple containing the x and y coordinates for the popup position.
setup_hoverable_element(root, thought_manager)
Sets up the hoverable text element in the root window. It inserts the main text, configures the textbox, and starts the background task to clean up undestroyed popups.
Parameters
root: The root window.
thought_manager: An instance of the ThoughtManager class.
cleanup_popups(root)
A background task that periodically checks for undestroyed popups and destroys them. It runs every 10 seconds.
Parameters
root: The root window.
Usage
Install Dependencies: Ensure that the required libraries (customtkinter, text_generator, colorama) are installed.
Run the Script: Execute the fairy_popup.py script.
Interact with the GUI: Hover over the hoverable words in the textbox to see popup boxes with associated thoughts.
def calculate_popup_position(x, y, popup_width, popup_height):
# Calculate the position of the popup at the cursor position
popup_x = x - popup_width // 2 # Center the popup horizontally
popup_y = y - popup_height + 150 # Position the popup above the cursor with an offset
return popup_x, popup_y
for word in thought_manager.hoverable_words:
start = "1.0"
while True:
start = text_widget.search(word, start, stopindex="end")
if not start:
break
end = f"{start}+{len(word)}c"
text_widget.tag_add("hoverable", start, end)
start = end
# Start the background task to clean up undestroyed popups
root.after(10000, cleanup_popups, root)
def cleanup_popups(root):
for widget in root.winfo_children():
if isinstance(widget, customtkinter.CTkToplevel) and widget.winfo_exists():
widget.destroy()
logging.info(f"{Fore.YELLOW}Undestroyed popup cleaned up{Style.RESET_ALL}")
# Schedule the cleanup task to run again after 10 seconds
root.after(10000, cleanup_popups, root)
if name == "main":
root = customtkinter.CTk()
root.geometry("300x200")
thought_manager = ThoughtManager()
setup_hoverable_element(root, thought_manager)
root.mainloop()
import customtkinter
from text_generator import generate_garbled_lorem_ipsum
import random
import logging
from colorama import Fore, Style, init
# Initialize colorama
init(autoreset=True)
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Set the appearance mode (dark theme)
customtkinter.set_appearance_mode("dark")
class ThoughtManager:
def __init__(self):
self.main_text = self.main_text_determiner()
self.hoverable_words = self.determiner_function(self.main_text)
self.thoughts = self.thought_function(self.main_text, self.hoverable_words)
def main_text_determiner(self):
return "This is the hover text. It can be dynamically set."
def determiner_function(self, main_text):
return ["hover", "can"]
def thought_function(self, main_text, hoverable_words):
thoughts = {}
for word in hoverable_words:
thoughts[word] = generate_garbled_lorem_ipsum()
return thoughts
class HoverableText(customtkinter.CTkTextbox):
def __init__(self, thought_manager, *args, **kwargs):
super().__init__(*args, **kwargs)
self.thought_manager = thought_manager
self.configure(wrap='word', height=50, width=250)
self.tag_config("hoverable", foreground="blue", underline=1)
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
self.current_popup = None # Track the current popup
def on_enter(self, event):
self.configure(cursor="hand2")
# Calculate the position of the cursor when it first hovers over the element
x, y = event.x_root, event.y_root
# Create a new popup at the cursor position
self.current_popup = create_popup(x, y, self.winfo_toplevel(), "Hover Text")
logging.info(f"{Fore.GREEN}Popup created for element{Style.RESET_ALL}")
def on_leave(self, event):
self.configure(cursor="")
if self.current_popup and self.current_popup.winfo_exists():
self.current_popup.destroy()
logging.info(f"{Fore.RED}Popup destroyed{Style.RESET_ALL}")
self.current_popup = None
def create_popup(x, y, root, text):
try:
popup = customtkinter.CTkToplevel(root)
popup.overrideredirect(True)
# Set transparency by matching the frame color to the popup's background
content_frame = customtkinter.CTkFrame(popup, corner_radius=10, fg_color=("transparent",))
content_frame.pack(padx=5, pady=5, expand=True, fill="both")
label = customtkinter.CTkLabel(content_frame, text=text, wraplength=200)
label.pack(padx=10, pady=10)
popup.update_idletasks()
popup_width, popup_height = popup.winfo_width(), popup.winfo_height()
popup_x, popup_y = calculate_popup_position(x, y, popup_width, popup_height)
popup.geometry(f"+{popup_x}+{popup_y}")
return popup
except Exception as e:
logging.error(f"{Fore.PURPLE}Error in create_popup: {e}{Style.RESET_ALL}")
return None
def calculate_popup_position(x, y, popup_width, popup_height):
# Adjust position to the right of the cursor, without a gap
popup_x = x + 1 # Position the popup immediately to the right of the cursor
popup_y = y - popup_height // 2 # Center the popup vertically relative to the cursor
return popup_x, popup_y
def setup_hoverable_element(root, thought_manager):
text_widget = HoverableText(thought_manager, root)
text_widget.pack(pady=20)
text_widget.insert("1.0", thought_manager.main_text)
text_widget.configure(state="disabled")
for word in thought_manager.hoverable_words:
start = "1.0"
while True:
start = text_widget.search(word, start, stopindex="end")
if not start:
break
end = f"{start}+{len(word)}c"
text_widget.tag_add("hoverable", start, end)
start = end
# Start the background task to clean up undestroyed popups
root.after(10000, cleanup_popups, root)
def cleanup_popups(root):
for widget in root.winfo_children():
if isinstance(widget, customtkinter.CTkToplevel) and widget.winfo_exists():
widget.destroy()
logging.info(f"{Fore.YELLOW}Undestroyed popup cleaned up{Style.RESET_ALL}")
# Schedule the cleanup task to run again after 10 seconds
root.after(10000, cleanup_popups, root)
if __name__ == "__main__":
root = customtkinter.CTk()
root.geometry("300x200")
thought_manager = ThoughtManager()
setup_hoverable_element(root, thought_manager)
root.mainloop()
Changes:
Dark Theme: Added customtkinter.set_appearance_mode("dark") to set the application to dark mode.
Transparent Frame: Used fg_color=("transparent",) for CTkFrame to attempt transparency.
Right Alignment of Popup: Adjusted calculate_popup_position to put the popup immediately to the right of the cursor.
Make sure to test this implementation and adjust further as per real-world observations, since transparency handling can vary across different systems and platforms.
import customtkinter
from text_generator import generate_garbled_lorem_ipsum
import random
import logging
from colorama import Fore, Style, init
# Initialize colorama
init(autoreset=True)
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Set the appearance mode (dark theme)
customtkinter.set_appearance_mode("dark")
class ThoughtManager:
def __init__(self):
self.main_text = self.main_text_determiner()
self.hoverable_words = self.determiner_function(self.main_text)
self.thoughts = self.thought_function(self.main_text, self.hoverable_words)
def main_text_determiner(self):
return "This is the hover text. It can be dynamically set."
def determiner_function(self, main_text):
return ["hover", "can"]
def thought_function(self, main_text, hoverable_words):
thoughts = {}
for word in hoverable_words:
thoughts[word] = generate_garbled_lorem_ipsum()
return thoughts
class HoverableText(customtkinter.CTkTextbox):
def __init__(self, thought_manager, *args, **kwargs):
super().__init__(*args, **kwargs)
self.thought_manager = thought_manager
self.configure(wrap='word', height=50, width=250)
self.tag_config("hoverable", foreground="blue", underline=1)
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
self.current_popup = None # Track the current popup
def on_enter(self, event):
self.configure(cursor="hand2")
# Calculate the position of the cursor when it first hovers over the element
x, y = event.x_root, event.y_root
# Create a new popup at the cursor position
self.current_popup = create_popup(x, y, self.winfo_toplevel(), "Hover Text")
logging.info(f"{Fore.GREEN}Popup created for element{Style.RESET_ALL}")
def on_leave(self, event):
self.configure(cursor="")
if self.current_popup and self.current_popup.winfo_exists():
self.current_popup.destroy()
logging.info(f"{Fore.RED}Popup destroyed{Style.RESET_ALL}")
self.current_popup = None
def create_popup(x, y, root, text):
try:
popup = customtkinter.CTkToplevel(root)
popup.overrideredirect(True)
# Correct transparency setting using a string
content_frame = customtkinter.CTkFrame(popup, corner_radius=10, fg_color='transparent')
content_frame.pack(padx=5, pady=5, expand=True, fill="both")
label = customtkinter.CTkLabel(content_frame, text=text, wraplength=200)
label.pack(padx=10, pady=10)
popup.update_idletasks()
popup_width, popup_height = popup.winfo_width(), popup.winfo_height()
popup_x, popup_y = calculate_popup_position(x, y, popup_width, popup_height)
popup.geometry(f"+{popup_x}+{popup_y}")
return popup
except Exception as e:
# Use Fore.MAGENTA for a purple-like color
logging.error(f"{Fore.MAGENTA}Error in create_popup: {e}{Style.RESET_ALL}")
return None
def calculate_popup_position(x, y, popup_width, popup_height):
# Adjust position to the right of the cursor, without a gap
popup_x = x + 1 # Position the popup immediately to the right of the cursor
popup_y = y - popup_height // 2 # Center the popup vertically relative to the cursor
return popup_x, popup_y
def setup_hoverable_element(root, thought_manager):
text_widget = HoverableText(thought_manager, root)
text_widget.pack(pady=20)
text_widget.insert("1.0", thought_manager.main_text)
text_widget.configure(state="disabled")
for word in thought_manager.hoverable_words:
start = "1.0"
while True:
start = text_widget.search(word, start, stopindex="end")
if not start:
break
end = f"{start}+{len(word)}c"
text_widget.tag_add("hoverable", start, end)
start = end
# Start the background task to clean up undestroyed popups
root.after(10000, cleanup_popups, root)
def cleanup_popups(root):
for widget in root.winfo_children():
if isinstance(widget, customtkinter.CTkToplevel) and widget.winfo_exists():
widget.destroy()
logging.info(f"{Fore.YELLOW}Undestroyed popup cleaned up{Style.RESET_ALL}")
# Schedule the cleanup task to run again after 10 seconds
root.after(10000, cleanup_popups, root)
if __name__ == "__main__":
root = customtkinter.CTk()
root.geometry("300x200")
thought_manager = ThoughtManager()
setup_hoverable_element(root, thought_manager)
root.mainloop()
Key Modifications:
Changed fg_color=("transparent",) to fg_color='transparent' for the CTkFrame.
Updated the logging color to Fore.MAGENTA instead of Fore.PURPLE.
Try running the script again with these changes. This should resolve the errors you encountered.
def create_popup(x, y, root, text):
try:
popup = customtkinter.CTkToplevel(root)
popup.overrideredirect(True)
content_frame = customtkinter.CTkFrame(popup, corner_radius=10, fg_color='transparent')
content_frame.pack(padx=5, pady=5, expand=True, fill="both")
label = customtkinter.CTkLabel(content_frame, text=text, wraplength=200)
label.pack(padx=10, pady=10)
popup.update_idletasks()
popup_width, popup_height = popup.winfo_width(), popup.winfo_height()
popup_x, popup_y = calculate_popup_position(x, y, popup_width, popup_height, root)
popup.geometry(f"+{popup_x}+{popup_y}")
return popup
except Exception as e:
logging.error(f"{Fore.MAGENTA}Error in create_popup: {e}{Style.RESET_ALL}")
return None
def calculate_popup_position(x, y, popup_width, popup_height, root):
# Get the screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# Calculate the new popup position
popup_x = x + 1 # Position the popup immediately to the right of the cursor
popup_y = y - popup_height // 2 # Center the popup vertically relative to the cursor
# Ensure the popup does not go out of the screen bounds
if popup_x + popup_width > screen_width:
popup_x = screen_width - popup_width # Align to the right edge
if popup_y + popup_height > screen_height:
popup_y = screen_height - popup_height # Align to the bottom edge
if popup_y < 0:
popup_y = 0 # Align to the top edge
return popup_x, popup_y
Explanation
Screen Size Awareness: We retrieve the current screen width and height using root.winfo_screenwidth() and root.winfo_screenheight().
Boundary Checks: We ensure the popup does not go beyond the screen's right or bottom edge, which would make it invisible or partially visible.
Vertical Adjustment: Similarly, if the calculated position causes the popup to start above the top of the screen, we adjust it.
This dynamic approach helps maintain the popup's visibility and correct positioning even when the screen size changes, such as during window minimize/maximize actions.
import customtkinter
from text_generator import generate_garbled_lorem_ipsum
import logging
from colorama import Fore, Style, init
# Initialize colorama
init(autoreset=True)
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(asctime)s - %(levelname)s - %(message)s')
# Set the appearance mode (dark theme)
customtkinter.set_appearance_mode("dark")
class ThoughtManager:
def __init__(self):
self.main_text = self.main_text_determiner()
self.hoverable_words = self.determiner_function(self.main_text)
self.thoughts = self.thought_function(self.main_text, self.hoverable_words)
def main_text_determiner(self):
return "This is the hover text. It can be dynamically set."
def determiner_function(self, main_text):
return ["hover", "can"]
def thought_function(self, main_text, hoverable_words):
thoughts = {}
for word in hoverable_words:
thoughts[word] = generate_garbled_lorem_ipsum()
return thoughts
class HoverableText(customtkinter.CTkTextbox):
def __init__(self, thought_manager, *args, **kwargs):
super().__init__(*args, **kwargs)
self.thought_manager = thought_manager
self.configure(wrap='word', height=50, width=250)
self.tag_config("hoverable", foreground="blue", underline=1)
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
self.current_popup = None # Track the current popup
self.in_popup = False # Track if the cursor is in the popup
def on_enter(self, event):
self.configure(cursor="hand2")
x, y = event.x_root, event.y_root
if not self.current_popup or not self.current_popup.winfo_exists():
self.current_popup = create_popup(x, y, self.winfo_toplevel(), "Hover Text", self)
logging.info(f"{Fore.GREEN}Popup created for element{Style.RESET_ALL}")
def on_leave(self, event):
if not self.in_popup:
self.configure(cursor="")
if self.current_popup and self.current_popup.winfo_exists():
self.current_popup.destroy()
logging.info(f"{Fore.RED}Popup destroyed{Style.RESET_ALL}")
self.current_popup = None
def create_popup(x, y, root, text, hoverable_text):
try:
popup = customtkinter.CTkToplevel(root)
popup.overrideredirect(True)
content_frame = customtkinter.CTkFrame(popup, corner_radius=10, fg_color='transparent')
content_frame.pack(padx=5, pady=5, expand=True, fill="both")
label = customtkinter.CTkLabel(content_frame, text=text, wraplength=200)
label.pack(padx=10, pady=10)
popup.update_idletasks()
popup_width, popup_height = popup.winfo_width(), popup.winfo_height()
popup_x, popup_y = calculate_popup_position(x, y, popup_width, popup_height, root)
popup.geometry(f"+{popup_x}+{popup_y}")
# Bind enter and leave events to the popup box
popup.bind("<Enter>", lambda e: on_popup_enter(hoverable_text))
popup.bind("<Leave>", lambda e: on_popup_leave(hoverable_text, popup))
return popup
except Exception as e:
logging.error(f"{Fore.MAGENTA}Error in create_popup: {e}{Style.RESET_ALL}")
return None
def on_popup_enter(hoverable_text):
# Set a flag to indicate that the cursor is in the popup
hoverable_text.in_popup = True
def on_popup_leave(hoverable_text, popup):
# Reset the flag and destroy the popup
hoverable_text.in_popup = False
if popup and popup.winfo_exists():
popup.destroy()
hoverable_text.current_popup = None
logging.info(f"{Fore.RED}Popup destroyed{Style.RESET_ALL}")
def calculate_popup_position(x, y, popup_width, popup_height, root):
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
popup_x = x + 1
popup_y = y - popup_height // 2
if popup_x + popup_width > screen_width:
popup_x = screen_width - popup_width
if popup_y + popup_height > screen_height:
popup_y = screen_height - popup_height
if popup_y < 0:
popup_y = 0
return popup_x, popup_y
def setup_hoverable_element(root, thought_manager):
text_widget = HoverableText(thought_manager, root)
text_widget.pack(pady=20)
text_widget.insert("1.0", thought_manager.main_text)
text_widget.configure(state="disabled")
for word in thought_manager.hoverable_words:
start = "1.0"
while True:
start = text_widget.search(word, start, stopindex="end")
if not start:
break
end = f"{start}+{len(word)}c"
text_widget.tag_add("hoverable", start, end)
start = end
root.after(10000, cleanup_popups, root)
def cleanup_popups(root):
for widget in root.winfo_children():
if isinstance(widget, customtkinter.CTkToplevel) and widget.winfo_exists():
widget.destroy()
logging.info(f"{Fore.YELLOW}Undestroyed popup cleaned up{Style.RESET_ALL}")
root.after(10000, cleanup_popups, root)
if __name__ == "__main__":
root = customtkinter.CTk()
root.geometry("300x200")
thought_manager = ThoughtManager()
setup_hoverable_element(root, thought_manager)
root.mainloop()
Explanation:
Popup Enter/Leave Binding: The popup binds to <Enter> and <Leave> events, maintaining a state (in_popup) that indicates whether the cursor is within the popup.
State Handling:
When the popup is entered, in_popup is set to True to indicate the cursor is in the popup and prevent the popup from closing.
When the popup is left, in_popup is reset to False, and the popup is allowed to close if the cursor has also left the HoverableText.
This way, the tooltip remains open as long as you move your cursor into it, and only closes when you leave both the text area and the tooltip.