下面我将详细讲解“基于Python制作三款起床闹钟的示例代码”的完整攻略。
简介
起床是每天必须要做的事情,但很多人都有困难。为了帮助你更容易地起床,我们提供了三个 Python 闹钟项目。这些闹钟可以让你自由选择你最喜欢的方式去唤醒你的晨感。
安装
使用这些 Python 闹钟项目,需要先安装 Python。请参阅Python网站获取有关如何在特定操作系统上安装 Python 的详细信息。Python版本应大于等于3.5。
安装 Python 后,我们需要安装两个必要的 Python 包:pygame
和 playsound
。使用以下命令在终端中安装它们。
pip install pygame
pip install playsound
项目一:数字闹钟
数字闹钟是我们第一个 Python 闹钟项目。它使用 Python 的 datetime 模块获取当前时间和设置闹钟时间。根据条件不断判断当前时间是否与闹钟时间一致,若一致则使用 tkinter 呈现消息框提醒你,直到你关闭消息框为止。下面是示例代码:
import tkinter
import datetime
import time
def set_alarm(alarm_time):
alarm_hour = alarm_time[0]
alarm_minute = alarm_time[1]
while True:
now = datetime.datetime.now()
current_hour = now.hour
current_minute = now.minute
if (alarm_hour == current_hour and alarm_minute == current_minute):
print("Time to Wake up")
break
def get_alarm_time():
alarm_input = input("Set the alarm time : [HH:MM] ")
try:
alarm_time = [int(n) for n in alarm_input.split(":")]
display_alarm_time = datetime.datetime.now().replace(hour=alarm_time[0],minute=alarm_time[1],second=0)
print("Alarm Set For :{}".format(display_alarm_time.strftime("%I:%M:%S %p")))
return alarm_time
except ValueError:
print("Invalid Time Entered")
return get_alarm_time()
alarm_time = get_alarm_time()
set_alarm(alarm_time)
项目二:游戏闹钟
游戏闹钟是我们第二个 Python 闹钟项目。它使用 pygame 模块生成一个易于播放的声音,并在触发闹钟时播放一个简单的游戏。你可以选择 Pygame 默认的 .wav 音频文件或者自己用音频剪辑软件制作自己的音频文件。下面是示例代码:
import pygame
import datetime
import time
pygame.init()
display_width = 800
display_height = 700
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Game Alarm Clock')
clock = pygame.time.Clock()
crash_sound = pygame.mixer.Sound("examples/alarm-clock/alarm_sound.wav")
def blit_text(surface, text, pos, font, color=pygame.Color('black')):
words = [word.split(' ') for word in text.splitlines()] # 2D array where each row is a list of words.
space = font.size(' ')[0] # The width of a space.
max_width, max_height = surface.get_size()
x, y = pos
for line in words:
for word in line:
word_surface = font.render(word, 0, color)
word_width, word_height = word_surface.get_size()
if x + word_width >= max_width:
x = pos[0] # Reset the x.
y += word_height # Start on new row.
surface.blit(word_surface, (x, y))
x += word_width + space
x = pos[0] # Reset the x.
y += word_height # Start on new row.
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',20)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
crash_sound.play()
pygame.display.update()
time.sleep(2)
def text_objects(text, font):
textSurface = font.render(text, True, pygame.Color('black'))
return textSurface, textSurface.get_rect()
def game_loop():
is_game_over = False
while not is_game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_game_over = True
gameDisplay.fill(pygame.Color('white'))
pygame.display.update()
clock.tick(60)
def set_alarm(game_time):
alarm_hour = game_time[0]
alarm_minute = game_time[1]
while True:
now = datetime.datetime.now()
current_hour = now.hour
current_minute = now.minute
if (alarm_hour == current_hour and alarm_minute == current_minute):
message_display("Time to Wake up")
game_loop()
break
def get_game_time():
alarm_input = input("Set the wakeup game time [HH:MM] :")
try:
alarm_time = [int(n) for n in alarm_input.split(":")]
display_alarm_time = datetime.datetime.now().replace(hour=alarm_time[0],minute=alarm_time[1],second=0)
print("Alarm is set to :{}".format(display_alarm_time.strftime("%I:%M:%S %p")))
return alarm_time
except ValueError:
print("Invalid time entered")
return get_game_time()
game_time = get_game_time()
set_alarm(game_time)
项目三:动画闹钟
动画闹钟是我们最后一个 Python 闹钟项目。它使用 PyQt5 创建了一个图形用户界面(GUI),在触发闹钟时会显示动画效果。这个过程需要有效益的计算机图形库 PyQt5 和样式表QSS。下面是示例代码:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 470, 430)
self.setWindowTitle('Animation Alarm')
self.label = QLabel(self)
pixmap = QPixmap('animation.gif')
self.label.setPixmap(pixmap)
self.label.setGeometry(0,-100,480,480)
self.timeEdit = QTimeEdit(self)
self.timeEdit.move(45,360)
btn1 = QPushButton("Set Alarm",self)
btn1.move(300,360)
btn1.clicked.connect(self.startTimer)
self.show()
def paintEvent(self, event):
qp = QPainter()
qp.begin(self)
self.drawRectangles(qp)
qp.end()
def drawRectangles(self, qp):
color = QColor(0, 0, 0)
color.setNamedColor('#d4d4d4')
qp.setPen(QPen(Qt.red, 4, Qt.SolidLine))
qp.setBrush(QBrush(Qt.SolidPattern))
qp.drawRect(20, 80, 400, 240)
def startTimer(self):
self.timer = QTimer(self)
self.timer.timeout.connect(self.countdown)
self.timer.start(1000)
def countdown(self):
timer_value = self.timeEdit.time().toString()
current_time = QDateTime.currentDateTime().toString()
if timer_value == current_time[11:16]:
QMessageBox.information(self,"Alert", "Time is up! Timer finished!")
self.timer.stop()
self.label.move(0,0)
else:
print("Still waiting...")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
以上就是三个 Python 闹钟项目的示例代码、操作文档及开发环境的详细攻略。希望对你的 Python 学习之旅有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:基于Python制作三款起床闹钟的示例代码 - Python技术站