gpt4 book ai didi

python - 在 python 中编程时钟时,如何允许用户输入自己的当前时间值?

转载 作者:太空宇宙 更新时间:2023-11-04 04:21:40 25 4
gpt4 key购买 nike

在与学徒招聘代理联系后,我接到了任务,要离开并为我的时钟编程。我目前有一个工作时钟,但我仍然不满意,因为必须在程序中实现当前时间才能使其作为可用时钟工作,而我希望用户能够这样做以使其更加用户友好。

我已经尝试删除预设小时、分钟和秒的位置,将其替换为以下内容:

hours = input("Set the amount of hours\n")
minutes = input("Set the amount of minutes\n")
seconds = input("Set the amount of seconds\n")

但是这会产生错误: 'TypeError: 无法将 'int' 对象隐式转换为 str'

它按计划在预设时间打开时钟,但它不会从这个时间开始向前计数。

hours = input("Set the amount of hours\n")
minutes = input("Set the amount of minutes\n")
seconds = input("Set the amount of seconds\n")

#hours=15
#minutes=5
#seconds=0

import time

from turtle import*
setup()
t1 = Turtle()

while True:
t1.clear()
t1.write(str(hours).zfill(2) + ":" + str(minutes).zfill(2) + ":"
+ str(seconds).zfill(2),
font=("arial", 60, "bold"))

seconds = seconds+1
time.sleep(1)

if seconds == 60:
seconds = 0
minutes = minutes+1

if minutes == 60:
minutes =0
hours = hours+1

if hours ==24:
seconds=0
minutes=0
hours=0

通常我希望 turtle 程序根据用户输入的方式打开显示时间,它确实这样做了,但是它崩溃了并且无法像人们期望的基本 24 小时时钟那样运行。

最佳答案

读取输入时,python 将输入的任何内容解释为字符串。所以 hours = input("Set the ...") 将小时设置为字符串。这在尝试将整数 (+1) 添加到字符串时会导致问题。

另外,以这种方式制作时钟要小心;程序本身的任何延迟都会导致时钟越来越不准时。

多一点:

  • minutes += 1 比 minutes = minutes + 1 更 pythonic
  • 尽量避免导入 *。它导入的内容远远超出必要的范围,并可能导致困惑的冲突。
  • 也应该是设置小时数;不是小时数

关于python - 在 python 中编程时钟时,如何允许用户输入自己的当前时间值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com