可以帮我看看我的这个多线程错误问题吗?
以下是我的代码:
# 闹钟
import threading
import time
import sys
import tkinter as tk
import pygame
# 获取当前时间
def get_time():
current_time = time.strftime("%H:%M:%S") # 获取当前时间并转化为字符串
return current_time # 返回当前系统时间
# 弹出提示窗口
def window():
global root
root = tk.Tk() # tkinter窗口初始化
root.title("闹钟") # 闹钟提醒窗口的标题
root.geometry("200x100+550+300") # 闹钟提醒窗口的大小和初始位置
root.resizable(False, False) # 闹钟提醒窗口的长和宽不可拉伸,即禁止调节窗口大小
root.label1 = tk.Label(root, text="当前时间为:" + get_time()) # 显示标签
root.label1.place(x=40, y=20) # 显示标签位于提醒窗口的位置
root.button = tk.Button(root, text="OK", command=ok_func) # “OK”按钮,command指令,点击后窗口自动销毁
root.button.place(x=75, y=60, width=50, height=20) # “OK”按钮的位置
root.mainloop() # 让闹钟提醒窗口保留在屏幕中
# “OK”按钮功能
def ok_func():
root.destroy() # 关闭弹窗
pygame.mixer.music.stop() # 闹钟音乐停止
# 播放音乐
def play_music():
file = '闹钟铃声.mp3' # 音乐路径
pygame.mixer.init() # 初始化
pygame.mixer.music.load(file) # 加载文件
pygame.mixer.music.play() # 播放音乐
if __name__ == '__main__':
print("----------添加闹钟----------")
print("输入的时间格式为:时:分(英文:号)")
print("请设定提醒时间:", end=' ') # end='',表示不换行,因为print()函数默认换行
object_time = str(input() + ':00') # 默认闹钟的提醒时间的秒位为00,即不需要设定提醒时间的秒数,比如:当时间到达17:49:00时闹钟提醒
while get_time() != object_time: # 当前时间不等于提醒时间时,进行以下过程
sys.stdout.flush() # 刷新时间
time.sleep(0.995) # 经过多次测试,由于程序有运行过程中的时间消耗造成的误差,需要每隔0.995秒刷新一次当前时间,才能较好地与当前系统时间进行比较
threads = [threading.Thread(target=play_music), threading.Thread(target=window)] # 多线程,同时运行两个函数,以达到同时出现弹窗和发出铃声提醒的效果
for t in threads:
t.start() # 线程开始