Search code examples
pythontkinterpywin32pynput

a click counter that displays how many times you clicked left mb using python 3.8 , tkinter , win32 and pynput


Here is the very basic example . I've found the displaying script from this website and copied the mouse listener from pynput's documentary . When i remove the counter part it succesfully displays the value of clickamount variable but when i add it back it doesnt display anything also it doesnt give any error message

#import things

from pynput.mouse import Listener
import tkinter, win32api, win32con, pywintypes

#variable defining

clickamount=0

#counter part using pynput

with Listener() as listener:
    listener.join()
def on_click(button, pressed):
    clickamount+=1

#display the amount

label = tkinter.Label(text=clickamount, font=('Times New Roman','80'), fg='black', bg='white')
label.master.overrideredirect(True)
label.master.geometry("+0+0")
label.master.lift()
label.master.wm_attributes("-topmost", True)
label.master.wm_attributes("-disabled", True)
label.master.wm_attributes("-transparentcolor", "white")

hWindow = pywintypes.HANDLE(int(label.master.frame(), 16))
# http://msdn.microsoft.com/en-us/library/windows/desktop/ff700543(v=vs.85).aspx
# The WS_EX_TRANSPARENT flag makes events (like mouse clicks) fall through the window.
exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)

label.pack()
label.mainloop()


Solution

  • Just use tkinter's inbuilt events and bindings:

    clickamount = 0
    
    def onclick(event):
        global clickamount
        clickamount+=1
    
    root = Tk()
    root.bind("<Button-1>", onclick)
    root.mainloop()
    

    Method with mouse:

    import mouse
    
    clickamount = 0
    
    def onclick():
        global clickamount
        clickamount+=1
        print(clickamount)
    
    root = Tk()
    mouse.on_click(onclick)
    root.mainloop()