你如何在python中使用按钮作为输入

时间:2015-01-13 14:18:49

标签: python button time

我需要创建一个计算汽车在已知距离(100米)上的速度的程序。我需要程序在用户按 Enter 时开始计时(这应该模拟汽车何时进入受监控的路段),当用户再次按 Enter 时停止计时,然后计算汽车的平均速度。

1 个答案:

答案 0 :(得分:1)

  

当用户按下Enter时开始计时(这应该模拟汽车何时进入受监控的路段),当用户再次按Enter键时停止计时,然后计算汽车的平均速度。

CLI版本:

#!/usr/bin/env python3
from time import monotonic as timer

input("Press Enter to start timer") # wait for the first Enter from the user
start = timer()
input("Press Enter to stop timer")
elapsed = timer() - start
print("Speed {speed:f} m/s".format(speed=100 / elapsed))

要创建GUI秒表,您可以使用tkinter

#!/usr/bin/env python3
from time import monotonic as timer
from tkinter import font, Tk, ttk

distance = 100 # meters
START, STOP = 'start', 'stop'

class Stopwatch(object):
    def __init__(self, parent):
        self.parent = parent
        # create a button, run `.toggle_button` if it is pressed
        self.button = ttk.Button(parent,text=START, command=self.toggle_button)
        self.button.grid(sticky='nwse') # lays out the button inside the parent

    def toggle_button(self, event=None):
        if self.button is None: # close parent window
            self.parent.destroy()
        elif self.button['text'] == START: # start timer
            self.start = timer()
            self.button['text'] = STOP
        elif self.button['text'] == STOP: # stop timer, show result
            elapsed = timer() - self.start
            self.button.destroy()
            self.button = None
            text = "Speed {:.2f} m/s".format(distance / elapsed)
            ttk.Label(self.parent, text=text, anchor='center').grid()

root = Tk() # create root window
root.protocol("WM_DELETE_WINDOW", root.destroy)  # handle root window deletion
root.bind('<Return>', Stopwatch(root).toggle_button) # handle <Enter> key
root.mainloop()

您可以按 Enter 并点击按钮调用.toggle_button()方法。

要使主窗口变大,请在root = Tk()行后添加:

root.title('Stopwatch') # set window title
root.geometry('400x300') # set window size
root.columnconfigure(0, weight=1) # children widgets may fill the whole space
root.rowconfigure(0, weight=1)
font.nametofont('TkDefaultFont').configure(size=25) # change default font size