I'm trying to get the mouse coordinates, with pynput, and see it with a GUI with PySimpleGUI but I am getting a lot of problens, and I don't know how can I do this.
I want to show the mouse coordinates at the "x - y" string below
import PySimpleGUI as sg
from pynput import mouse
sg.theme("DarkAmber")
layout = [[sg.Text("Mouse Coord")],
[sg.Text("x - y")]]
window = sg.Window("Mouse Coord 1.0", layout, keep_on_top = True)
while True:
event, values = window.read()
print(event, values)
if event == sg.WIN_CLOSED or event == 'Exit':
break
window.close()
Not sure why you need the mouse coordinate, following code demo the way to get it by PySimpleGUI.
import PySimpleGUI as sg
sg.theme("DarkAmber")
layout = [[sg.Text("Mouse Coord:"), sg.Text(size=20, key='Coordinate')]]
window = sg.Window("Mouse Coord", layout, finalize=True)
window.bind('<Motion>', 'Motion')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == 'Motion':
e = window.user_bind_event
window['Coordinate'].update(f'({e.x}, {e.y})')
window.close()
You can get the screen coordinate by e.x_root
and e.y_root
, like
window['Coordinate'].update(f'({e.x_root}, {e.y_root})')
The '<Motion>'
in tkinter only work when mouse on the tkinter window, following code demo the way using pynput
library to capture the motion event, then pass it to PySimpleGUI.
from pynput.mouse import Listener
import PySimpleGUI as sg
def on_move(x, y):
window.write_event_value('Motion', (x, y))
sg.theme("DarkAmber")
layout = [[sg.Text("Mouse Coord:"), sg.Text(size=20, key='Coordinate')]]
window = sg.Window("Mouse Coord", layout, finalize=True, enable_close_attempted_event=True)
listener = Listener(on_move=on_move)
listener.start()
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSE_ATTEMPTED_EVENT:
listener.stop()
break
elif event == 'Motion':
x, y = values[event]
window['Coordinate'].update(f'({x}, {y})')
window.close()