我正在制作CPS计数器,但计时器遇到问题?

时间:2019-08-18 03:50:58

标签: python tkinter

我对使用python的tkinker还是一个新手(确实是新手),并且在制作和显示CPS计算器的计时器时遇到了一些麻烦(例如:http://www.mcrpg.com/kohi-click-test)。

我尝试了几种解决方案,但似乎都没有用。 示例一:

while True:
    if seconds > -10:
        time.sleep(1)
        seconds += 1
        secs.configure(text=seconds)

在此示例中,它使window.mainloop()无法访问。 如果没有while True:window.mainloop()可达,则仅更新“秒”一次。 (0-> 1)

它说不包括我的整个代码,希望我只包括了必要的代码。

计时器代码:

# Seconds

secs = Label(window, text=0, fg='white', bg='blue')
secs.grid(column=6, row=6)


if seconds > -10:
    time.sleep(1)
    seconds += 1
    secs.configure(text=seconds)

window.mainloop()

我的变量:

from tkinter import *
# noinspection PyUnresolvedReferences
import time

window = Tk()

clicks = 0

window.title("CPS TEST")

window.geometry('500x500')

lbl = Label(window, text='CPS TEST', bg='orange')

lbl.grid(column=0, row=0)

clicks1 = 0

seconds = 0

我希望窗口中的secs每秒更新一次,向变量中添加一个,使数字增加。反正有我可以解决的吗?

3 个答案:

答案 0 :(得分:0)

与大多数GUI工具包一样,

Tkinter是一个事件驱动系统。为了使代码正常运行,您的代码基本上是mainloop()中的访客,必须从中进行调用。 因此,您的代码必须存在于回调中。您可以说有两种回调;

  • 附加到小部件的回调(例如,按下按钮时的回调)
  • 计时器调用的
  • 回调(使用Tk.after

使用第一类回调,您可以在每次调用回调时记录datetime.datetime。将datetime附加到global列表中。

使用第二种回调(例如每秒调用一次),您可以计算datetime列表中后续项之间的差。这将为您提供timedelta个对象。然后将列表设置为空列表。对时间增量求平均值,如果平均值不为0,则将其取反。这样可以得到CPS。使用它来更新显示。

答案 1 :(得分:0)

以罗兰·史密斯(Roland Smith)的答案为基础,要多次重复root.after(),可以使其递归。所以看起来像这样

from tkinter import *

root = Tk()

label = Label(root, text='Time: ')
label.pack()

time = Label(root, text=0)
time.pack()

def update_time():
    time.configure(text=time.cget('text') + 1)
    root.after(1000, update_time)

root.after(1000, update_time)

root.mainloop()

答案 2 :(得分:0)

嗯,这个问题很老了,我的代码没有使用 tkinter,但我还是想分享一下

from pynput.mouse import Listener
from time import sleep, time
from threading import Thread
import os.path
from pyfiglet import Figlet

f = Figlet ( font = "roman" )
print ( "\x1b[?25l" )
clicks = [ ]

def reduce ( ) :
  while True :
    removed = [ i for i in clicks if time ( ) - i > 1 ]
    for i in removed : clicks.remove ( i )
    #print ( "\x1b[1;1H\x1b[J" )
    print ( f.renderText ( str ( len ( clicks ))))
    if os.path.isfile ( "stop" ) :
      print ( "\x1b[?25h" )
      return

def on_click ( x, y, button, pressed ):
  if pressed and str ( button ) == "Button.left" :
    global clicks
    clicks += [ time ( )]

x = Thread ( target = reduce )
x.start ( )

with Listener ( on_click = on_click ) as listener:
  listener.join ( )

它还创建了一个整洁的控制台窗口,里面有一个告诉你 CPS 的大数字