开发Python闹钟时while循环重复要求赋值的问题求助
闹钟脚本循环重复请求设置时间的问题解决
问题描述
开发闹钟脚本时遇到以下问题:
- 运行脚本后,while循环持续要求设置时间,即便相关变量已被赋值
- 预期脚本等待到设置时间与当前时间匹配后播放闹钟,但实际一直停留在输入环节
问题代码
from datetime import datetime import pygame pygame.init() now = datetime.now() time = now.strftime("%H:%M:%S") hours = time[:2] minutes = time[3:5] seconds = time[6:] if int(hours) <12: hoursdisplayed = f"{hours} AM" else: hoursdisplayed = f"{int(hours)-12} PM" alarm = pygame.mixer.Sound("C:\Users\bambini\Downloads\alarmclock.mp3") while True: selectedhours = None selectedminutes = None selectedseconds = None if selectedhours == None and selectedminutes == None and selectedseconds == None: selectedhours = int(input("Select the hour you want to wake up\n")) selectedminutes = int(input("Select the minute you want to wake up\n")) selectedseconds = int(input("Select the second you want to wake up\n")) if selectedhours >= 12: selectedhours -= 12 elif hours == selectedhours and minutes == selectedminutes and seconds == selectedseconds: alarm.play()
问题原因
- 变量重置问题:selectedhours、selectedminutes、selectedseconds被定义在while循环内部,每次循环都会被重置为None,导致每次都会触发输入逻辑
- 时间未实时更新:当前时间只在脚本启动时获取一次,后续循环不会更新时间,无法匹配实时时间
- 类型不匹配:hours、minutes、seconds是字符串类型,selectedhours等是整数类型,直接比较永远不相等
- 12小时制转换逻辑错误:输入的小时转换为12小时制后,和当前时间的24小时制字符串无法匹配
修复后的代码
from datetime import datetime import pygame import time pygame.init() # 先获取闹钟时间,只执行一次 selectedhours = int(input("Select the hour you want to wake up (24小时制)\n")) selectedminutes = int(input("Select the minute you want to wake up\n")) selectedseconds = int(input("Select the second you want to wake up\n")) alarm = pygame.mixer.Sound("C:\\Users\\bambini\\Downloads\\alarmclock.mp3") while True: # 实时获取当前时间 now = datetime.now() current_hour = now.hour current_minute = now.minute current_second = now.second # 显示当前时间(可选) if current_hour <12: hoursdisplayed = f"{current_hour} AM" else: hoursdisplayed = f"{current_hour-12} PM" print(f"Current time: {hoursdisplayed} {current_minute}:{current_second}", end="\r") # 比较时间(统一用24小时制整数比较) if current_hour == selectedhours and current_minute == selectedminutes and current_second == selectedseconds: print("\nAlarm triggered!") alarm.play() # 播放后可以选择退出循环或持续播放 # 这里让闹钟播放3秒后退出 time.sleep(3) break # 每秒检查一次,减少资源占用 time.sleep(1)
修复说明
- 将闹钟时间输入移到循环外部,避免每次循环重置变量
- 在循环内部实时获取当前时间,确保时间是最新的
- 统一使用整数类型的小时、分钟、秒进行比较,避免类型不匹配问题
- 加入time.sleep(1)减少循环频率,降低资源消耗
- 添加了当前时间的实时显示,符合你提到的hoursdisplayed变量的使用需求
- 修复了路径中的转义字符问题(原路径中的\需要改为\,否则会被解析为转义符)
内容的提问来源于stack exchange,提问作者tommaso bernkopf
相关产品推荐
相关产品推荐

