How to wait for a mouse click? How to wait for a mouse click? tkinter tkinter

How to wait for a mouse click?


Why do you use the win32api to get the mousebutton press and location? Tkinter can do this just fine. You can use the OK button to activate a new left-mousebutton bind and let that bind disable itself when it has been called. You can even change the cursor to indicate that the program is in a state where you expect the user to click on a location:

from tkinter import *def enable_mouseposition():    window.bind("<Button-1>", get_mouseposition)    window.config(cursor="crosshair")def get_mouseposition(event):    print(event.x, event.y)    window.unbind("<Button-1>")    window.config(cursor="arrow")window = Tk()window.geometry("700x500")window.title("Testing")b = Button(window, text="OK", command=enable_mouseposition)b.grid(row=0, column=2, sticky=W)window.mainloop()

I now understand you want to be able to get the click everywhere on the screen, not just in the tkinter window. In that case you will need something besides tkinter, like win32api. Also, because you can not generate a tkinter event by clicking outside the window, you would need a loop that checks the button state repeatedly until the button is clicked. You can make a loop in tkinter without blocking the mainloop using after:

from tkinter import *import win32apidef enable_mouseposition():    window.after(10, get_mouseposition)def get_mouseposition():    state_left = win32api.GetKeyState(0x01)    if state_left == -127 or state_left == -128:        xclick, yclick = win32api.GetCursorPos()        print(xclick, yclick)    else:        window.after(10, get_mouseposition)window = Tk()window.geometry("700x500")window.title("Testing")b = Button(window, text="OK", command=enable_mouseposition)b.grid(row=0, column=2, sticky=W)window.mainloop()