首页 > 解决方案 > 在 tkinter 中使用 after 创建多个计时器

问题描述

我在应用程序中使用 after 来更新时间、日期、天气和其他内容。但是当我尝试使用 after 运行多个计时器时遇到了困难。单击另一个计时器按钮时,计时器停止。

import time
import datetime
from tkinter import *
import tkinter as tk
from tkinter import messagebox
import tkinter.font as TkFont
from time import strftime


def stop_drink():
    global count_flag_drink
    count_flag_drink = False


def count_up_drink():
    global count_flag_drink
    count_flag_drink = True
    start = time.time()
    time.process_time()
    while True:
        if count_flag_drink == False:
            break
        elapsed = time.time() - start
        hours, mins, secs = str(datetime.timedelta(seconds=elapsed)).split(':')
        hour_drink.set(hours)
        minute_drink.set(mins)
        second_drink.set(secs.split('.')[0])
        time.sleep(0.1)
        root.update()

    root.after(1000, count_up_drink)


def count_down_drink():
    global count_flag_drink
    count_flag_drink = True

    try:
        temp = int(hour_drink.get()) * 3600 + \
            int(minute_drink.get()) * 60 + int(second_drink.get())

    except:
        print("Please input the right value")
    while temp > -1:
        if count_flag_drink == False:
            break
        mins, secs = divmod(temp, 60)

        hours = 0
        if mins > 60:

            hours, mins = divmod(mins, 60)

        hour_drink.set(f"{hours:2d}")
        minute_drink.set(f"{mins:2d}")
        second_drink.set(f"{secs:2d}")

        root.update()
        time.sleep(1)

        if (temp == 0):
            messagebox.showinfo("Time Countdown", "Time's up ")

        temp -= 1

    root.after(1000, count_down_drink)


def stop_food():
    global count_flag_food
    count_flag_food = False


def count_up_food():
    global count_flag_food
    count_flag_food = True

    start = time.time()
    time.process_time()
    while True:
        if count_flag_food == False:
            break
        elapsed = time.time() - start
        hours, mins, secs = str(datetime.timedelta(seconds=elapsed)).split(':')
        hour_food.set(hours)
        minute_food.set(mins)
        second_food.set(secs.split('.')[0])
        time.sleep(0.1)
        root.update()

    root.after(1000, count_up_food)


def count_down_food():
    global count_flag_food
    count_flag_food = True

    try:
        temp = int(hour_food.get()) * 3600 + \
            int(minute_food.get()) * 60 + int(second_food.get())

    except:
        print("Please input the right value")
    while temp > -1:
        if count_flag_food == False:
            break
        mins, secs = divmod(temp, 60)

        hours = 0
        if mins > 60:

            hours, mins = divmod(mins, 60)

        hour_food.set(f"{hours:2d}")
        minute_food.set(f"{mins:2d}")
        second_food.set(f"{secs:2d}")

        root.update()
        time.sleep(1)

        if (temp == 0):
            messagebox.showinfo("Time Countdown", "Time's up ")

        temp -= 1

    root.after(1000, count_down_food)


root = Tk()

root.geometry("700x500")

root.rowconfigure((0, 1, 2, 3, 4, 5, 6), weight=1)
root.columnconfigure((0), weight=8,  uniform='a')
root.columnconfigure((7), weight=1,  uniform='a')
root.columnconfigure((1, 2, 3, 4, 5, 6), weight=4,  uniform='a')

root.title("2 Timers")
root.configure(bg='#282932')
root.resizable(width=0, height=0)

hour_drink = StringVar()
minute_drink = StringVar()
second_drink = StringVar()

hour_drink.set("04")
minute_drink.set("00")
second_drink.set("00")

hour_food = StringVar()
minute_food = StringVar()
second_food = StringVar()

hour_food.set("04")
minute_food.set("00")
second_food.set("00")


drink_event_name = Entry(root, width=10, font=(
    'Fira Code', 18), fg='white', bg='#5789d9', justify='center', borderwidth=6).grid(row=0, column=0)

drink_hourEntry = Entry(root, width=3, font=('Fira Code', 16), fg='#99ceff', bg='#5a605c', justify='center', borderwidth=1,
                        textvariable=hour_drink).grid(row=0, column=1)

drink_minuteEntry = Entry(root, width=3, font=('Fira Code', 16), fg='#99ceff', bg='#5a605c', justify='center', borderwidth=1,
                          textvariable=minute_drink).grid(row=0, column=2)


drink_secondEntry = Entry(root, width=3, font=('Fira Code', 16), fg='#99ceff', bg='#5a605c', justify='center', borderwidth=1,
                          textvariable=second_drink).grid(row=0, column=3)


drink_btn_up = Button(root, text='UP',  fg='#99ceff', bg='#32475a',
                      font=('Fira Code', 12), borderwidth='7', width=7,  command=count_up_drink).grid(row=0, column=4)


drink_btn_down = Button(root, text='DOWN',  fg='#99ceff', bg='#32475a',
                        font=('Fira Code', 12), borderwidth='7', width=7, command=count_down_drink).grid(row=0, column=5)

drink_btn_stop = Button(root, text='STOP',  fg='#99ceff', bg='#32475a',
                        font=('Fira Code', 12), borderwidth='7', width=7, command=stop_drink).grid(row=0, column=6)

food_event_name = Entry(root, width=10, font=(
    'Fira Code', 18), fg='white', bg='#5789d9', justify='center', borderwidth=6).grid(row=1, column=0)

food_hourEntry = Entry(root, width=3, font=('Fira Code', 16), fg='#99ceff', bg='#5a605c', justify='center', borderwidth=1,
                       textvariable=hour_food).grid(row=1, column=1)


food_minuteEntry = Entry(root, width=3, font=('Fira Code', 16), fg='#99ceff', bg='#5a605c', justify='center', borderwidth=1,
                         textvariable=minute_food).grid(row=1, column=2)


food_secondEntry = Entry(root, width=3, font=('Fira Code', 16), fg='#99ceff', bg='#5a605c', justify='center', borderwidth=1,
                         textvariable=second_food).grid(row=1, column=3)


food_btn_up = Button(root, text='UP',  fg='#99ceff', bg='#32475a',
                     font=('Fira Code', 12), borderwidth='7', width=7,  command=count_up_food).grid(row=1, column=4)

food_btn_down = Button(root, text='DOWN',  fg='#99ceff', bg='#32475a',
                       font=('Fira Code', 12), borderwidth='7', width=7, command=count_down_food).grid(row=1, column=5)

food_btn_stop = Button(root, text='STOP',  fg='#99ceff', bg='#32475a',
                       font=('Fira Code', 12), borderwidth='7', width=7, command=stop_food).grid(row=1, column=6)


root.mainloop()

更新。 我发现这个解决方案很容易就我的目的进行扩展。[使用类的计时器][1]

  [1]: https://stackoverflow.com/questions/44372046/tkinter-timer-to-start-at-0-on-button-click

标签: python-3.xtkintertime

解决方案


推荐阅读