我希望用python做一个CPS(ClickPerSecond)应用程序,我做了一些研究,最后有了下面的代码:
from pynput.mouse import Listener, Button, Controller
import time
new = 0
old = 0
def on_click(x, y, button, pressed):
global old
global new
if pressed:
new = time.time()
print("Click Detected")
CPS = round((1/(old-new))*-1)
old = new
print(CPS)
with Listener(on_click=on_click) as listener:
listener.join()此代码检测鼠标右键和左键并计算我的CPS。但我想要一个接口与tkinter,只写我的CPS的文本变量。最大的问题是,我想点击屏幕上的任何地方,这样就会检测到它。但我不知道如何将它插入到我的代码中。T-T
你能帮我吗?
发布于 2020-11-22 03:32:36
这里有一个简单的解决方案,我相信它能做你想要的。此方法不需要pynput和time。相反,我们利用了tkinter的after和bind_all方法。
import tkinter as tk
root = tk.Tk()
cps_lbl = tk.Label(root)
cps_lbl.grid()
#reset cps to zero every second
def reset_counter():
global cps
cps = 0
root.after(1000, reset_counter)
#increment cps and publish results
def click_counter(event):
global cps
cps += 1
cps_lbl['text'] = f'{cps} clicks per second'
root.bind_all('<1>', click_counter) #left click
root.bind_all('<3>', click_counter) #right click
reset_counter()
root.mainloop() 或者,您可以直接bind到root并强制焦点停留在root上,而不是bind_all。
替换:
root.bind_all('<1>', click_counter) #left click
root.bind_all('<3>', click_counter) #right click使用:的
root.bind('<1>', click_counter)
root.bind('<3>', click_counter)
root.focus_force()发布于 2020-11-22 03:42:59
对于不完全完整问题,有些讽刺的答案是在tk上创建全屏画布,并对其点击量进行计数。例如:
import tkinter
root = tkinter.Tk()
root.overrideredirect(True)
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
var = StringVar()
label = Label(root, textvariable=var, relief=RAISED)
var.set("Hey!? Are You Click'n or what?") # set it to Your CPS
label.pack()
root.mainloop()https://stackoverflow.com/questions/64946288
复制相似问题