【发布时间】:2021-08-12 11:07:57
【问题描述】:
我创建了一个 tkinter 闹钟,设置闹钟后没有响应。闹钟声音正在播放,但之后我必须退出应用程序并重新运行代码以再次设置闹钟。我已经分享了应用程序的代码和屏幕截图。
from tkinter import
import datetime
import time
from playsound import playsound
def Alarm(set_alarm_timer):
while True:
time.sleep(1)
actual_time = datetime.datetime.now()
cur_time = actual_time.strftime("%H:%M:%S")
cur_date = actual_time.strftime("%d/%m/%Y")
msg="Current Time: "+str(cur_time)
print(msg)
if cur_time == set_alarm_timer:
playsound("Audio.mp3")
break
def get_alarm_time():
alarm_set_time = f"{hour.get()}:{min.get()}:{sec.get()}"
Alarm(alarm_set_time)
window = Tk()
window.title("Alarm Clock")
window.geometry("400x160")
window.config(bg="#922B21")
window.resizable(width=False,height=False)
time_format=Label(window, text= "Remember to set time in 24 hour format!", fg="white",bg="#922B21",font=("Arial",15)).place(x=20,y=120)
addTime = Label(window,text = "Hour Min Sec",font=60,fg="white",bg="black").place(x = 210)
setYourAlarm = Label(window,text = "Set Time for Alarm: ",fg="white",bg="#922B21",relief = "solid",font=("Helevetica",15,"bold")).place(x=10, y=40)
hour = StringVar()
min = StringVar()
sec = StringVar()
hourTime= Entry(window,textvariable = hour,bg = "#48C9B0",width = 4,font=(20)).place(x=210,y=40)
minTime= Entry(window,textvariable = min,bg = "#48C9B0",width = 4,font=(20)).place(x=270,y=40)
secTime = Entry(window,textvariable = sec,bg = "#48C9B0",width = 4,font=(20)).place(x=330,y=40)
submit = Button(window,text = "Set Your Alarm",fg="Black",bg="#D4AC0D",width = 15,command = get_alarm_time,font=(20)).place(x =100,y=80)
window.mainloop()
【问题讨论】:
-
在使用
tkinter时不要使用while True循环或time.sleep,除非您知道它可能导致的所有问题。查看.after脚本。 -
您在 GUI 程序中使用了
while循环。如果您不使用线程,则不能这样做,否则您的 GUI 将冻结,如您所见。您应该查看.after()方法以便稍后运行。 -
@quamrana 您提到了线程,所以我不得不提到
tkinter不是线程安全的,因此不应从其他线程访问它。但我同意你所说的一切。 -
@TheLizzard:你说得很对,
tkinter不是线程安全的。不要在多个线程中使用函数来更新 gui 元素。但是,只要只有主线程更新 gui,您仍然可以在tkinter程序中使用线程。其他线程可以做他们喜欢的任何其他处理,例如互联网请求、数据库访问、文件处理。如果需要将任何数据返回到 GUI,则可以将数据推送到主线程服务的队列中。