【问题标题】:time function always gives me 0.0 output时间函数总是给我 0.0 输出
【发布时间】:2020-12-05 08:28:23
【问题描述】:

我正在尝试制作一个 CPS 计数器,当我达到 100 次点击时,它应该打印“测试”并打印达到 100 次点击所需的时间。但它总是给出 0.0 作为时间输出。

import tkinter
import time

counter = tkinter.Tk()

clicks = 0

def addClick():
    global clicks
    clicks = clicks + 1
    lbl.configure(text=clicks)

    start = time.time()
    if clicks == 100:
        print("test")
        end = time.time()
        print(start - end)

lbl = tkinter.Label(counter, text = clicks)
lbl.pack()

btn = tkinter.Button(counter, text="Click here", command=addClick)
btn.pack()


counter.mainloop()

【问题讨论】:

  • 您每次调用addClick 时设置start,就在您的if 条件之前。你应该在函数外设置start

标签: python tkinter time


【解决方案1】:
... 
start = time.time()
if clicks == 100:
    print("test")
    end = time.time()
    print(start - end)

每次点击后你都会不断重启start。一个可能的解决方案是仅在第一次单击后启动它。这将要求 start 也是一个全局变量。

还请注意,您应该使用end - start,而不是start - end

clicks = 0
start = None
...
global clicks
global start
...

if clicks == 1:
    # instantiating 'start' only if it was the first click
    start = time.time()
elif clicks == 100:
    print("test")
    end = time.time()
    print(end - start)

然而,使用全局变量是一种代码异味和反模式,我们在这么小的程序中已经有两个。

您可以尝试将它们包装在一个数据结构中,例如 dict:

import tkinter
import time

counter = tkinter.Tk()

data = {'clicks': 0, 'start': None}

def addClick():
    data['clicks'] += 1
    lbl.configure(text=data['clicks'])

    if data['clicks'] == 1:
        # instantiating 'start' only if it was the first click
        data['start'] = time.time()
    elif data['clicks'] == 100:
        print("test")
        end = time.time()
        print(end - data['start'])

lbl = tkinter.Label(counter, text=data['clicks'])
lbl.pack()

btn = tkinter.Button(counter, text="Click here", command=addClick)
btn.pack()

counter.mainloop()

另一个现实世界的合适解决方案是将整个 tkinter 应用程序包装在一个类中,该类可以跟踪自己的状态。

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2014-12-12
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多