首页 > 解决方案 > python中不规则的计时器

问题描述

我正在 python 中为倒数计时器创建一个代码,其中包含时间和 tkinter 库,但不是规则。cronometer 部分只显示 spin.get

Windows 10 和 python 3,在 sublime 文本上运行

import tkinter as tk
from tkinter import*
import time
window=Tk()
window.title('Programa')
window.geometry('300x500')
window.resizable(True, True)
window.config(bg='dark grey')
f=Frame(window, width=300, height=500)
f.pack()
f.config(bg='dark grey')
var =IntVar()
var.set(30)
spin = Spinbox(f, from_=0, to=100, width=5, bg=('dark grey'), 
textvariable=var)
spin.place(x=125, y=100)
text1=Label(f, text='Tiempo de ejercicio:', bg=('dark grey'))
text1.place(x=5, y=100)
def codigo():
#here is when not works, on the for i in range
    f2=Frame(f, width=300, height=500)
    f2.pack()
    f2.config(bg='dark grey')
    text2=Label(f, text=spin.get(), font=('Arial Bold', 90), bg=('dark grey'))
    text2.place(x=80, y=200)
    for i in range((spin.get),1,1)
    time.sleep(1)
btn1 = tk.Button(f, text = 'Empezar', command = codigo, bg=('dark grey'))
btn1.pack()
btn1.place(x=150, y=150)

window.mainloop()

cronometer 部分只显示 spin.get,但我需要时间减少

标签: pythonpython-3.xtkinter

解决方案


您需要的是另一个倒计时并在一秒钟后调用自身的函数:

# keep code as you have it before codigo
text2 = None
def timer():
    text2['text'] = str(timer.current)
    timer.current = timer.current - 1
    if timer.current >= 0:
        f.after(1000, timer)
def codigo():

    global text2
    f2=Frame(f, width=300, height=500)
    f2.pack()
    f2.config(bg='dark grey')
    text2=Label(f, text=spin.get(), font=('Arial Bold', 90), bg=('dark grey'))
    text2.place(x=80, y=200)
    timer.current = int(spin.get())
    timer()

推荐阅读