带 tkinter 的秒表?

Stopwatch with tkinter?

我接受了使用 python 和 tkinter 制作魔方计时器的任务。我想知道是否有一种方法可以使用“输入”键或 space 栏 start/stop 那个秒表。我已经能够在不使用 tkinter window 的情况下实现这一点,但我无法弄清楚如何让 tkinter 检测按键而无需更改输入字段。我附上的代码是没有 tkinter 的秒表功能。

def stopwatch():
    import time
    print("")

    start = input("Press 'Enter' to start timer")

    begin = time.time()
    endtimer = input("Press 'Enter' to end the timer")
    end = time.time()

    time = end-begin
    time = float(round(time,3))
    text = ""
    if time >= 60.999:
        newTime = time/60
        text += ("The final time was " + str(newTime) + " minutes")
    else:
        text += ("The final time was " + str(time) + " seconds")

    return text

使用 TKINTER 的文件

from tkinter import *
from timer import *
from scrambler import *
from colors import *
window = Tk()
window.title("Bryson's Scrambler")
lbl = Label(window, text=sprint(valid(s)))
lbl.grid(column=0, row=0)
lbl2 = Label(window, text=stopwatch())
lbl2.grid(column=10, row=10)
window.mainloop()

我已经制作了一个秒表的小原型,所以只需复制此处的代码即可。看起来它会解决你的需求

import tkinter as tk
import time


class Timer:
    def __init__(self):
        self.root = tk.Tk()
        self.sv = tk.StringVar()
        self.start_time = None
        self.is_running = False

        self.make_widgets()
        self.root.bind('<Return>', self.startstop)
        self.root.mainloop()

    def make_widgets(self):
        tk.Label(self.root, textvariable=self.sv, font='ariel 15').pack()

        btn_frame = tk.Frame(self.root)
        btn_frame.pack()
        tk.Button(btn_frame, text='Start', command=self.start).pack(side=tk.LEFT)
        tk.Button(btn_frame, text='Stop', command=self.stop).pack(side=tk.RIGHT)

    def start(self):
        if not self.is_running:
            self.start_time = time.time()
            self.timer()
            self.is_running = True

    def timer(self):
        self.sv.set(self.format_time(time.time() - self.start_time))
        self.after_loop = self.root.after(50, self.timer)

    def stop(self):
        if self.is_running:
            self.root.after_cancel(self.after_loop)
            self.is_running = False

    def startstop(self, event=None):
        if self.is_running:
            self.stop()
        else:
            self.start()

    @staticmethod
    def format_time(elap):
        hours = int(elap / 3600)
        minutes = int(elap / 60 - hours * 60.0)
        seconds = int(elap - hours * 3600.0 - minutes * 60.0)
        hseconds = int((elap - hours * 3600.0 - minutes * 60.0 - seconds) * 10)
        return '%02d:%02d:%02d:%1d' % (hours, minutes, seconds, hseconds)


Timer()