基于Python制作三款起床闹钟的示例代码

yizhihongxing

下面我将详细讲解“基于Python制作三款起床闹钟的示例代码”的完整攻略。

简介

起床是每天必须要做的事情,但很多人都有困难。为了帮助你更容易地起床,我们提供了三个 Python 闹钟项目。这些闹钟可以让你自由选择你最喜欢的方式去唤醒你的晨感。

安装

使用这些 Python 闹钟项目,需要先安装 Python。请参阅Python网站获取有关如何在特定操作系统上安装 Python 的详细信息。Python版本应大于等于3.5。

安装 Python 后,我们需要安装两个必要的 Python 包:pygameplaysound。使用以下命令在终端中安装它们。

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技术站

(0)
上一篇 2023年6月3日
下一篇 2023年6月3日

相关文章

  • Python sqlalchemy时间戳及密码管理实现代码详解

    十分感谢你对“Python sqlalchemy时间戳及密码管理实现代码详解”的关注。 本文主要介绍如何使用 Python 的 sqlalchemy 库实现时间戳和密码管理功能。 一、使用 sqlalchemy 实现时间戳功能 在使用 sqlalchemy 的 ORM 进行数据库操作时,可以通过指定字段类型为 DateTime 类型,并设置为默认从数据库获取…

    python 2023年6月2日
    00
  • python ETL工具 pyetl

    什么是PyETL PyETL是Python ETL(Extract, Transform, Load)工具包,它可以帮助用户从多种数据源中提取数据,对数据进行转换和清洗后,将它们保存到文件、数据库或其他数据存储介质中。 PyETL的安装方法 PyETL可以通过pip安装,执行以下命令即可: pip install pyetl PyETL的使用方法 PyETL…

    python 2023年6月3日
    00
  • python3中zip()函数使用详解

    Python3中zip()函数使用详解 介绍 zip() 函数可以将多个可迭代对象(例如列表、元组、字典等)中对应位置的元素打包成一个元组,并返回由这些元组组成的迭代器。新的迭代器生成的元素个数由输入的可迭代对象中元素数量最少的那个确定。 语法 zip([iterable, …]) 参数 iterable(可迭代对象): 一个或多个可迭代对象,例如列表、…

    python 2023年5月14日
    00
  • python使用XPath解析数据爬取起点小说网数据

    下面是详细讲解“python使用XPath解析数据爬取起点小说网数据”的完整攻略: 第一步:安装必要的库 使用XPath解析数据需要安装lxml库。 pip install lxml 第二步:发送请求 在这里,我们使用requests库发起请求,并将HTML文档作为response变量保存。 import requests url = ‘https://ww…

    python 2023年5月14日
    00
  • Python 实现取矩阵的部分列,保存为一个新的矩阵方法

    实现取矩阵的部分列并保存为一个新的矩阵有以下几个步骤: 步骤 1:安装依赖库 要实现此任务,需要首先安装以下两个依赖库: Numpy: 用于处理数据 Pandas: 用于读取、处理和保存数据到文件 可以通过以下命令进行安装: pip install numpy pandas 步骤 2:读取原始矩阵数据 读取原始矩阵数据可以通过 Pandas 库中的 read…

    python 2023年6月5日
    00
  • Python控制台输出时刷新当前行内容而不是输出新行的实现

    为了实现Python控制台输出时刷新当前行内容而不是输出新行,我们需要用到sys模块以及对应的stdout和flush方法。 具体步骤如下: 导入sys模块 首先,在Python文件或控制台中导入sys模块,以便使用相关方法。可以使用以下命令导入sys模块: import sys 使用stdout方法替换输出 将标准输出(一般指print函数输出)替换成sy…

    python 2023年6月3日
    00
  • Python中的几种矩阵乘法(小结)

    Python中的几种矩阵乘法(小结) 矩阵乘法在机器学习和深度学习中被广泛应用,Python中也提供了多种实现方式。本文将介绍常用的几种矩阵乘法实现方式。 原生Python实现 Python提供了原生的矩阵乘法实现方式,即使用for循环遍历每个元素进行计算。这种方式实现简单,但效率较低,适合处理小规模的矩阵。 def matrix_multiply(a, b…

    python 2023年6月6日
    00
  • 利用Python发送 10 万个 http 请求

    以下是Python发送10万个http请求的攻略,具体分为以下几个步骤: 1. 安装必要的库 使用Python发送http请求需要用到requests库,可通过以下命令安装: pip install requests 2. 编写发送请求的Python脚本 按照以下格式编写Python脚本: import requests # 设置要发送请求的url url …

    python 2023年5月19日
    00
合作推广
合作推广
分享本页
返回顶部