Home > OS >  Using Tkinter to draw and track a mouse pointer
Using Tkinter to draw and track a mouse pointer

Time:06-29

im still learning to use Python and Tkinter. I have created a bit of code which (i thought) should create a canvas with 2 dots on and afterwards continuously printers the position of the mouse curser

    from tkinter import *
from win32 import win32gui
win = Tk()

def mouse_pos():
    flags, hcursor, (x, y) = win32gui.GetCursorInfo()
    return {"x": x, "y": y}

win.geometry("1500x900")
win.configure(background="black")

g_circle = Canvas(win, width=100, height=100, bg="black", bd=1, highlightthickness=0)
g_circle.place(x=100, y=100, in_=win)
g_circle.create_oval(50, 50, 100, 100, fill="green", offset="200,200", outline="white")

b_circle = Canvas(win, width=100, height=100, bg="black", bd=1, highlightthickness=0)
b_circle.place(x=1300, y=700, in_=win)
b_circle.create_oval(50, 50, 100, 100, fill="blue", outline="white")


while True:
    print(mouse_pos())
    win.mainloop()

I know there is an infinite loop but i am just testing it for now.

This issue is that when i run this code a TK window opens of the canvas with 2 circles and then a cmd displays an single value for x and y coordinate in text. The coordinates do not continue to update unless i close the TK window and i dont know why.

Ill post a screenshot in hopes it helps.

Any help is appreciated.

The two windows which open

cmd with mouse curser position

CodePudding user response:

win.mainloop() will block the while loop until the main window is closed.

You can use .after() to replace the while loop:

...
def mouse_pos():
    # no need to use external module to get the mouse position
    #flags, hcursor, (x, y) = win32gui.GetCursorInfo()
    x, y = win.winfo_pointerxy()
    print({"x": x, "y": y})
    # run mouse_pos() again 10 microseconds later
    win.after(10, mouse_pos)
...
''' don't need the while loop
while True:
    print(mouse_pos())
    win.mainloop()
'''
# start the "after loop"
mouse_pos()
win.mainloop()
  • Related