【发布时间】:2019-11-12 09:45:46
【问题描述】:
我正在尝试制作一个闹钟应用程序:闹钟应该在预设的时间响起。如果没有 tkinter,我的代码完全可以正常工作,但是使用 tkinter 它根本不起作用。 在原始代码中有一个 while 循环,我注意到并读到它不能与 tkinter 结合使用。我决定摆脱循环,但现在当我输入时间时警报会立即响起。
我已经阅读了有关使用 r.after(time_ms, function()) 的信息。但我不知道如何在我的代码中正确实现它。我读过它必须在函数的末尾和 r.mainloop() 之前,但我无法让它工作。有人能帮帮我吗?非常感谢你! 我已经阅读了很多关于此的或 stackoverflow 帖子,但我没有足够的经验来让它与这些答案一起工作。 :(
import tkinter as tk
from datetime import datetime, date
import time
from pygame import mixer
r = tk.Tk()
r.title('Smart Watch')
def alarm_sound():
mixer.init()
mixer.music.load('Wecker-sound.mp3')
def end():
mixer.init()
mixer.music.stop()
def display_output():
hour = entry_hour.get()
int_hour = int(hour)
minute = entry_minute.get()
int_minute = int(minute)
second = entry_second.get()
int_second = int(second)
confirmation_message = ('Alarm has been set for ' + hour + ':' +
minute + ':' + second + '.')
text_label['text'] = confirmation_message
if (time.localtime().tm_hour == hour and
time.localtime().tm_min == entry_minute.get() and
time.localtime().tm_sec == entry_second.get()):
alarm_sound()
mixer.music.play()
message = tk.Label(r, text='What is the alarm message you\'d like to receive when the alarm goes off?',
font=('Roboto-regular', 12), fg='black')
message.pack()
entry_message = tk.Entry(r, width=45)
entry_message.pack()
enter_hour = tk.Label(r, text='Enter the hour for the alarm to go off: ',
font=('Roboto-regular', 12), fg='black')
enter_hour.pack()
entry_hour = tk.Entry(r, width=10)
entry_hour.pack()
enter_minute = tk.Label(r, text='Enter the minute for the alarm to go off: ',
font=('Roboto-regular', 12), fg='black')
enter_minute.pack()
entry_minute = tk.Entry(r, width=10)
entry_minute.pack()
enter_second = tk.Label(r, text='Enter the second for the alarm to go off: ',
font=('Roboto-regular', 12), fg='black')
enter_second.pack()
entry_second = tk.Entry(r, width=10)
entry_second.pack()
text_label = tk.Label(r, font=('Roboto-regular', 12, 'bold'),
fg='tomato')
text_label.pack()
submit_button = tk.Button(r, text='Submit',
fg='black', width=30, height=2, relief='groove',
cursor='hand2', command=display_output)
submit_button.pack()
snooze_button = tk.Button(r, text='Snooze alarm',
fg='black',
width=30, height=2, relief='groove',
cursor='hand2', command=end)
snooze_button.pack()
r.mainloop()
# The original code without tkinter has the while loop like this:
while True:
if time.localtime().tm_hour == hr and time.localtime().tm_min == mn and time.localtime().tm_sec == sc:
print(message)
break
alarm_Sound()
mixer.music.play()
【问题讨论】:
-
使用
after更改时钟时间的示例:furas/tkitner/clock-function 它不使用while True,但它使用update_time中的after再次运行update_time所以它可以工作像循环。 -
顺便说一句:
after(...)作为第二个参数需要没有()的函数名称 -
谢谢。我试过不带 () 的函数名称,但随后我收到一条错误消息,提示“参数错误:必须是取消、空闲、信息或整数”。
-
总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图)放在有问题的(不是评论)中。还有其他有用的信息。
标签: python loops tkinter while-loop