python闹钟(线程+tkinter+pygame)

一.需求及分析

开发一个闹钟,当时间到达你设定的时间的时候,系统自动播放音乐。用到的库,tkinter,pygame,threading,time。由于设置闹钟时要不断得循环判断当前时间与设定时间是否相同,此时while循环会与tkinter的mainloop产生矛盾,会导致页面卡死,此时可设置多线程解决这个问题。

二.代码

播放音乐功能
def play_music():
    #str.set("时间到了")
    filepath = r"小传奇_Mr_128K.mp3";
    pygame.mixer.init()
    # 加载音乐
    pygame.mixer.music.load(filepath)
    pygame.mixer.music.play(start=0.0)
    # 播放时长,没有此设置,音乐不会播放,会一次性加载完
    time.sleep(120)
    pygame.mixer.music.stop()

单纯地导入pygame运行时会有提醒

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html

这时如果想去掉这个提醒可以在import pygame之前加入

from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
多线程的调用

这里设置一个Toplevel,用于实时时间的更新,实时时间的操作是设置一个label,然后更新这label的text值,这里用到一个非常使用的参数

str = StringVar()
l = Label(window_sign_up, textvariable=str,fg = 'red').place(x=80, y=10)
str.set(times)  #times为自己得到的实时时间

在这里插入图片描述
在循环判断过程中,由于用到while循环判断当前时间与设定时间是否一样,但是while却与tkinter的mianloop矛盾,此时多线程则发挥了很重要的作用

    #获取实时时间
    def gg1():
        # g = gg12()
        index = 0
        try:
            my_hour,my_minute = start()
        except:
            messagebox.showwarning("提醒","请注意:是否为中文输入法的:")
            index = 1
        if(index == 0):
        	#布局Toplevel
            window_sign_up = Toplevel(window)
            window_sign_up.attributes("-toolwindow", 1)
            window_sign_up.wm_attributes("-topmost", 1)
            window_sign_up.geometry('200x100+400+150')
            Label(window_sign_up, text='当前时间为: ').place(x=0, y=10)
            window_sign_up.title('Chanwj')
            b1 = Button(window_sign_up, text=' 退出 ', command=window.quit,fg = 'red')
            b1.place(x=50, y=50)
            str = StringVar()
            l = Label(window_sign_up, textvariable=str,fg = 'red').place(x=80, y=10)
            cw = 1



            #while循环
            while cw == 1:
                t = time.localtime()  # 当前时间的纪元值
                fmt = "%H %M"
                times = "%H : %M : %S"
                #获取当前时间
                now = time.strftime(fmt, t)  # 将纪元值转化为包含时、分的字符串
                times = time.strftime(times, t)   #显示的时间
                now = now.split(' ')
                hour = now[0]
                minute = now[1]
                str.set(times)
                if (hour == my_hour and minute == my_minute):
                    str.set("时间到了")
                    play_music()

                #print("时间到嘞")
                time.sleep(0.95)

#获取用户输入的时间
    def start():
        timea = var_usr_name.get()
        my_hourtotal = timea.split(":")  # 时间
        print(my_hourtotal)
        my_hour = my_hourtotal[0]  # 小时
        my_minute = my_hourtotal[1]  # 分钟
        return my_hour,my_minute
    def ff1():
        try:
            ff()
        except:
            messagebox.showwarning("请注意:是否为中文输入法的:")
    #开线程
    def ff():
        print("fffff")
        thread = threading.Thread(target=gg1)
        # make test_loop terminate when the user exits the window
        thread.daemon = True
        thread.start()
总体代码思路
import pygame
import time  # 导入此模块,获取当前时间
from tkinter import *
from tkinter import messagebox #弹窗
import threading
def GUI_TIME():
    window = Tk()
    window.title('欢迎使用Chanwj闹钟')
    window.geometry('505x430+300+100')
    canvas = Canvas(window, height=500, width=500)
    image_file = PhotoImage(file='ChanWJ.gif')
    image = canvas.create_image(0, 0, anchor='nw', image=image_file)
    canvas.pack(side='top')
    Label(window, text='添加闹钟: ').place(x=130, y=200)
    Label(window,text = "本软件仅用于学习用途",fg = 'red').place(x = 200,y = 80)
    var_usr_name = StringVar()
    var_usr_name.set('24:59')
    entry_usr_name = Entry(window, textvariable=var_usr_name, background='pink')
    entry_usr_name.place(x=250, y=200)


    '''
    中间插入上面的4个函数
    '''

    btn_sign_up = Button(window, text=' 开始 ', command=lambda: ff())
    btn_sign_up.place(x=130, y=300)
    b1 = Button(window, text=' 退出 ', command=window.quit)

    b1.place(x=250, y=300)
    #设置疑问功能
    b2 = Button(window,text = " ? ",command = problem_mail)
    b2.place(x=420,y=390)
    window.mainloop()

    
"""
这里放一个play_music函数
def play_music():
"""
def problem_mail():
    messagebox.showinfo("开发与疑问,版本2020.05.13.01","1.使用时输入时间,如24:59中的:请用中文的:\n2.联系我1595846471c@gmail.com\n3.下版本将加入世界闹钟以及闹钟推迟功能")

GUI_TIME()

打包成软件后
在这里插入图片描述
运行截图
在这里插入图片描述
在这里插入图片描述
完整代码关注公众号,回复100903可以得到。
在这里插入图片描述

  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值