-1

所以我使用 python3 和 tkinter 做了一个时钟,它并不特别,所以我想在每一个小时过去时添加一个声音,我尝试了 time.sleep 和 .after 两者都不起作用这里是我的代码:

from tkinter import *
from playsound import playsound


root = Tk()
root.title("Timer")


def one_hour_l8r():
    playsound('one hour later.mp3') #this is a file i downloaded it is the time card from sponge bob
    pass


def clock():
    hour = strftime("%I")
    mins = strftime("%M")
    secs = strftime("%S")
    day = strftime("%A")
    am_pm = strftime("%p")
    time.config(text=day + "|" + hour + ":" + mins + ":" + secs + " " + am_pm)

    time.after(60000 * 60, one_hour_l8r)
    time.after(1000, clock)


time = Label(root, text="", font=("Helivatica", 48), bg="black", fg="#00b9bc")
time.pack()

clock()

root.mainloop()
4

1 回答 1

1

设置第一次调用的延迟,然后使用延迟调用相同的方法。

from tkinter import *
from playsound import playsound
from datetime import datetime

root = Tk()
root.title("Timer")

def one_hour_l8r():
    playsound('one hour later.mp3') #this is a file i downloaded it is the time card from sponge bob
    time.after(60000 * 60, one_hour_l8r)  # wait one hour, then recall same function
    
def clock():
    d = datetime.now()
    hour = d.strftime("%I")
    mins = d.strftime("%M")
    secs = d.strftime("%S")
    day =  d.strftime("%A")
    am_pm = d.strftime("%p")
    time.config(text=day + "|" + hour + ":" + mins + ":" + secs + " " + am_pm)

    time.after(1000, clock)  # wait one second, update clock again
    
time = Label(root, text="", font=("Helivatica", 48), bg="black", fg="#00b9bc")
time.pack()

clock()  # start clock
time.after(60000 * 60, one_hour_l8r) # wait one hour then call sound function

root.mainloop()
于 2020-08-03T16:25:42.337 回答