【问题标题】:How do you use a button as an input in python [closed]你如何在python中使用按钮作为输入[关闭]
【发布时间】:2015-03-11 12:45:40
【问题描述】:

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

【问题讨论】:

  • 你是说现实世界的汽车追踪?你应该寻找图像处理
  • SO 不是代码创建服务,您需要自己完成大部分工作。我会建议您查看模块 time,用于计时,tkinter 用于按钮/GUI。阅读这些内容,如果您对自己尝试制作的程序有疑问,请询问。
  • 对问题更准确。你知道如何接受用户输入吗?如何获得时间?如何计算给定距离和时间的速度?
  • 我为您提供了一个基本的可能的时间测量解决方案。正如我所说的一个可能的解决方案(不是唯一的)

标签: python button time


【解决方案1】:

用户按回车开始计时(本意是模拟汽车进入监控路段),再次按回车停止计时,然后计算汽车的平均速度。

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

【讨论】:

    猜你喜欢
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多