调整闹钟时间以匹配python中的时钟时间

发布于 2024-12-03 13:36:52 字数 5331 浏览 2 评论 0原文

我刚刚学习 Python,作为朋友向我建议的基本挑战之一,我一直在研究闹钟。我成功制作了一个在预定时间播放 .wav 声音的闹钟。现在我一直在使用 Pygame 作为 GUI,一切都很好,直到我必须设置按钮来调整闹钟时间。看看当我将闹钟时间与时钟时间进行比较时,时钟时间是字符串形式,因此闹钟时间也必须如此。但按钮无法从字符串中进行 + 或 - 操作,所以我有点卡住了。我尝试了将其变成字符串的方法,但到目前为止一切都相当不成功。想知道这里是否有人有建议。

这是代码:

#!/usr/bin/python
import os.path, sys, datetime, time
import os, sys, math
import pygame, random
from pygame.locals import *

main_dir = os.path.split(os.path.abspath(__file__))[0]
data_dir = os.path.join(main_dir, 'data')
currenttime = datetime.datetime.now()
clocktime = currenttime.strftime("%H:%M")
alarmtime = "13:23"
pygame.init()

#Screen and background
width, height = 600, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Alarm Clock")
background = pygame.image.load(os.path.join(data_dir, 'diamondplate.jpg'))
background = pygame.transform.scale(background, (width, height))

#Current time
font = pygame.font.Font(None, 250)
text = font.render("%s" % clocktime, True, (255,140,0), (0,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery - 200

#Alarm time
text2 = font.render("%s" % '00:00', True, (255,140,0), (0,0,0))
text2Rect = text2.get_rect()
text2Rect.centerx = screen.get_rect().centerx
text2Rect.centery = screen.get_rect().centery + 200

#Alarm noise
def alarmsound(file_path=os.path.join(main_dir, 'data', 'boom.wav')):
    pygame.mixer.init(11025)
    sound = pygame.mixer.Sound(file_path)
    channel = sound.play()
    pygame.time.wait(1000)

#Image load function
def load_image(file):
    file = os.path.join(data_dir, file)
    surface = pygame.image.load(file)
    return surface.convert_alpha()

#Hour arrow up
class Hourup(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self,self.groups)
        image = load_image('arrowup.png')
        image = pygame.transform.scale(image, (85,85))
        self.image = image
        self.rect = self.image.get_rect()
        surface = pygame.display.get_surface()
        self.area = surface.get_rect()
        self.rect.bottomleft = text2Rect.topleft

    def click_check(self,eventpos):
        if self.rect.collidepoint(eventpos):
            pass

    def update(self):
        pass

#Hour arrow down
class Hourdown(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self,self.groups)
        image = load_image('arrowdown.png')
        image = pygame.transform.scale(image, (85,85))
        self.image = image
        self.rect = self.image.get_rect()
        surface = pygame.display.get_surface()
        self.area = surface.get_rect()
        self.rect.bottom = text2Rect.top
        self.rect.left = 159

    def click_check(self,eventpos):
        if self.rect.collidepoint(eventpos):
            pass    

    def update(self):
        pass

#Minute arrow up
class Minuteup(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self,self.groups)
        image = load_image('arrowup.png')
        image = pygame.transform.scale(image, (85,85))
        self.image = image
        self.rect = self.image.get_rect()
        surface = pygame.display.get_surface()
        self.area = surface.get_rect()
        self.rect.bottomright = (442,414)

    def click_check(self,eventpos):
        if self.rect.collidepoint(eventpos):
            pass

    def update(self):
        pass

#Minute arrow down
class Minutedown(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self,self.groups)
        image = load_image('arrowdown.png')
        image = pygame.transform.scale(image, (85,85))
        self.image = image
        self.rect = self.image.get_rect()
        surface = pygame.display.get_surface()
        self.area = surface.get_rect()
        self.rect.bottomright = text2Rect.topright

    def click_check(self,eventpos):
        if self.rect.collidepoint(eventpos):
            pass

    def update(self):
        pass


#Groups
allsprites = pygame.sprite.Group()
Hourup.groups = allsprites
Hourdown.groups = allsprites
Minutedown.groups = allsprites
Minuteup.groups = allsprites
hourup = Hourup()
hourdown = Hourdown()
minutedown = Minutedown()
minuteup = Minuteup()
clickableobjects = [hourup, hourdown, minutedown, minuteup]

def main():
    while 1:
        currenttime = datetime.datetime.now()
        clocktime = currenttime.strftime("%H:%M")
        screen.blit(background,(0,0))
        text = font.render("%s" % clocktime, True, (255,140,0), (0,0,0))
        text2 = font.render("%s" % alarmtime, True, (255,140,0), (0,0,0))
        screen.blit(text,textRect)
        screen.blit(text2,text2Rect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                sys.exit()
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    for object in clickableobjects:
                        object.click_check(event.pos)

        if clocktime == alarmtime and soundcheck = False:
            alarmsound()
            soundcheck = True
        allsprites.draw(screen)
        allsprites.update()
        pygame.display.update()
        pygame.display.flip

if __name__ == '__main__':
    main()

I'm just learning Python, and as one of the basic challenges that were suggested to me by friends I've been working on an alarm clock. I successfully made an alarm clock that played a .wav sound at a predetermined time. Now I've been using Pygame for a GUI, and it all worked great, until I had to set the buttons to adjust the alarm time. See when I compare the alarm time to the clock time, the clock time is in string form, so the alarm time has to be as well. But the buttons are unable to + or - from a string, so I'm kind of stuck. I tried ways of turning it into a string, but everything has been fairly unsuccessful so far. Wondering if anyone here had a suggestion.

Here's the code:

#!/usr/bin/python
import os.path, sys, datetime, time
import os, sys, math
import pygame, random
from pygame.locals import *

main_dir = os.path.split(os.path.abspath(__file__))[0]
data_dir = os.path.join(main_dir, 'data')
currenttime = datetime.datetime.now()
clocktime = currenttime.strftime("%H:%M")
alarmtime = "13:23"
pygame.init()

#Screen and background
width, height = 600, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Alarm Clock")
background = pygame.image.load(os.path.join(data_dir, 'diamondplate.jpg'))
background = pygame.transform.scale(background, (width, height))

#Current time
font = pygame.font.Font(None, 250)
text = font.render("%s" % clocktime, True, (255,140,0), (0,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery - 200

#Alarm time
text2 = font.render("%s" % '00:00', True, (255,140,0), (0,0,0))
text2Rect = text2.get_rect()
text2Rect.centerx = screen.get_rect().centerx
text2Rect.centery = screen.get_rect().centery + 200

#Alarm noise
def alarmsound(file_path=os.path.join(main_dir, 'data', 'boom.wav')):
    pygame.mixer.init(11025)
    sound = pygame.mixer.Sound(file_path)
    channel = sound.play()
    pygame.time.wait(1000)

#Image load function
def load_image(file):
    file = os.path.join(data_dir, file)
    surface = pygame.image.load(file)
    return surface.convert_alpha()

#Hour arrow up
class Hourup(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self,self.groups)
        image = load_image('arrowup.png')
        image = pygame.transform.scale(image, (85,85))
        self.image = image
        self.rect = self.image.get_rect()
        surface = pygame.display.get_surface()
        self.area = surface.get_rect()
        self.rect.bottomleft = text2Rect.topleft

    def click_check(self,eventpos):
        if self.rect.collidepoint(eventpos):
            pass

    def update(self):
        pass

#Hour arrow down
class Hourdown(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self,self.groups)
        image = load_image('arrowdown.png')
        image = pygame.transform.scale(image, (85,85))
        self.image = image
        self.rect = self.image.get_rect()
        surface = pygame.display.get_surface()
        self.area = surface.get_rect()
        self.rect.bottom = text2Rect.top
        self.rect.left = 159

    def click_check(self,eventpos):
        if self.rect.collidepoint(eventpos):
            pass    

    def update(self):
        pass

#Minute arrow up
class Minuteup(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self,self.groups)
        image = load_image('arrowup.png')
        image = pygame.transform.scale(image, (85,85))
        self.image = image
        self.rect = self.image.get_rect()
        surface = pygame.display.get_surface()
        self.area = surface.get_rect()
        self.rect.bottomright = (442,414)

    def click_check(self,eventpos):
        if self.rect.collidepoint(eventpos):
            pass

    def update(self):
        pass

#Minute arrow down
class Minutedown(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self,self.groups)
        image = load_image('arrowdown.png')
        image = pygame.transform.scale(image, (85,85))
        self.image = image
        self.rect = self.image.get_rect()
        surface = pygame.display.get_surface()
        self.area = surface.get_rect()
        self.rect.bottomright = text2Rect.topright

    def click_check(self,eventpos):
        if self.rect.collidepoint(eventpos):
            pass

    def update(self):
        pass


#Groups
allsprites = pygame.sprite.Group()
Hourup.groups = allsprites
Hourdown.groups = allsprites
Minutedown.groups = allsprites
Minuteup.groups = allsprites
hourup = Hourup()
hourdown = Hourdown()
minutedown = Minutedown()
minuteup = Minuteup()
clickableobjects = [hourup, hourdown, minutedown, minuteup]

def main():
    while 1:
        currenttime = datetime.datetime.now()
        clocktime = currenttime.strftime("%H:%M")
        screen.blit(background,(0,0))
        text = font.render("%s" % clocktime, True, (255,140,0), (0,0,0))
        text2 = font.render("%s" % alarmtime, True, (255,140,0), (0,0,0))
        screen.blit(text,textRect)
        screen.blit(text2,text2Rect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                sys.exit()
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    for object in clickableobjects:
                        object.click_check(event.pos)

        if clocktime == alarmtime and soundcheck = False:
            alarmsound()
            soundcheck = True
        allsprites.draw(screen)
        allsprites.update()
        pygame.display.update()
        pygame.display.flip

if __name__ == '__main__':
    main()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薄情伤 2024-12-10 13:36:52

您正在寻找 strptime() 它将字符串转换为日期时间实例。

请参阅此处了解如何正确使用它。

比较两个日期时间实例将为您提供一个 timedelta 实例,您可以阅读有关 在这里。本质上,它会给你两个时间之间的差异,精确到毫秒。

了解有关日期时间、时间和日历模块的所有内容。一旦你学会了用 python 处理时间和日期就会变得非常容易。

You are looking for strptime() which will convert a string to a datetime instance.

see here for how to properly use it.

Comparing two datetime instances will give you a timedelta instance which you can read about here. Essentially it will give you the difference between the two times to the nearest milisecond.

Learn everything you can about the datetime, time, and calendar modules. Once you learn those dealing with times and dates in python becomes really easy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文