如何每小时显示一个紧急窗口?

2024-09-29 23:27:55 发布

您现在位置:Python中文网/ 问答频道 /正文

使用tkinter,我正在做一个紧急窗口来提醒我喝水。在这一点上它是有效的,但现在我希望def trinke_wasser的部分每小时重复一次。我试过使用time模块,但最后我不知道在哪里写它

这是我的密码:

from tkinter import *
from PIL import Image
from PIL import ImageTk

fenstern = Tk()
fenstern.title("Warnung")
fenstern.geometry("900x600")
datei = Image.open('wasser_pic.png')
bild = ImageTk.PhotoImage(datei)
img = Label(fenstern, image = bild)
img.place(x=0, y=0)

def choice(option):

    pop.destroy()


def trinke_wasser():

    global pop
    fenstern.wm_state('iconic')

    pop = Toplevel(fenstern)
    pop.title('popup')
    pop.geometry("900x600")
    back= Label(pop, image = bild)
    back.place(x=0, y=0)

    rhamen = Frame(pop, bg = "white")
    rhamen.pack(pady = 5)

    yes = Button(rhamen, text = "YES", command = lambda: choice ("yes"), bg = "orange")
    yes.grid(row=0, column=1)

die_Taste = Button(fenstern, text = "Beginnen", command = trinke_wasser )
die_Taste.pack(pady=100)

fenstern.mainloop()

Tags: fromimageimportpiltitletkinterdefpop
2条回答

在当前程序中,只需按一次键即可执行trinke_wasser()函数。您要做的是打开一个调度程序函数,该函数每小时调用一次该函数。 但您必须允许此功能永久终止。因此,您需要一个全局布尔变量,可以关闭该变量以结束循环。(您也可以通过强制方式结束程序执行,但这并不好)

因此,您要做的是通过在脚本开头添加import time来导入时间库。 定义了fenstern之后,只要不将其设为false,只需将True属性添加到此窗口即可:fenstern.running = True

然后,您可以使您的计划程序运行:

def nerv_mich(delay = 3600):
    while fenstern.running:
        trinke_wasser()
        time.sleep(3600)

此功能将永远运行,并要求您每3600秒喝水一次

您只需调整第一个按钮的命令:

die_Taste = Button(fenstern, text = "Beginnen", command = nerv_mich)

现在,您只需使用yes定义之后的第二个按钮将其关闭

fertig = Button(rhamen, text = "Fertig jetzt!", command = lambda: choice ("fertig"), bg = "orange")
    yes.grid(row=2, column=1)

最后,您必须更改函数choice(),以便在传递给它的选项为"fertig"之后真正结束整个过程:

def choice(option):
    pop.destroy()
    if option=="fertig": fenstern.running=False

这应该行得通。您还可以使用fentstern.destroy()在此时完全结束您的程序。老实说,您可能并不真正需要这个初始窗口

在时间库中,有一个睡眠函数,它等待指定的秒数。如果我们计算一小时或3600秒的秒数。我们可以调用sleep函数,它将精确等待1小时

import time

time.sleep(3600)

所以如果你把sleep函数放在trinke_wasser函数的末尾。它会告诉你喝水,等一个小时,然后一遍又一遍地喝水

相关问题 更多 >

    热门问题