Access mouse position from anywhere!
ChatGPT-4 (may 24 version)
“In DearPyGUI, the
add_mouse_move_handler
function is used to register a callback function which will be automatically triggered whenever the mouse moves. This function does not allow you to manually retrieve mouse coordinates at any given time, it only passes the coordinates to the callback function when the mouse movement event occurs.However, you can create a global variable, or better, a class to store the latest mouse position whenever the mouse moves. Here is an example using a class:
import dearpygui.dearpygui as dpg class MousePosition: def __init__(self): self.x = 0 self.y = 0 def update(self, sender, app_data): self.x, self.y = app_data mouse_position = MousePosition() def mouse_move_handler(sender, app_data): mouse_position.update(sender, app_data) dpg.create_context() with dpg.handler_registry(): dpg.add_mouse_move_handler(callback=mouse_move_handler) with dpg.window(label="Example Window"): # Add your UI elements here... dpg.create_viewport(title='Example: Mouse Move Handler', width=600, height=300) dpg.setup_dearpygui() dpg.show_viewport() dpg.start_dearpygui() dpg.destroy_context()
In this code,
MousePosition
is a class that maintains the latest x
and y
mouse position. The mouse_move_handler
function is a callback function that updates the global mouse_position
object whenever the mouse moves. You can access the latest mouse position at any time by referring to mouse_position.x
and mouse_position.y
.Remember to adjust this code according to your GUI structure and needs.”