使用python执行计时器任务

2024-06-16 10:21:47 发布

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

我想在计时器达到8时将其重置为0,并应休眠5秒,显示计时器值为0,然后再次从零重新启动并重复。 当linemode == 'dashed':但当我的当前代码达到8时,它显示8,其中我想显示0 5秒。我已经发布了完整的代码片段,以及代码必须执行预期的代码片段。谢谢你的帮助

代码片段:-

if ton > ontym:
               if linemode == 'dashed':
                   counter=0                   
                   lbl['text']='00'
                   sleep(offtym)

                   ton=-1                   
                   lbl.after(1000, count)
               else:                                            
                   lbl.after(1000, count)
            else:
               lbl.after(1000, count)

完整代码片段:-

#!/usr/bin/env python
from  Tkinter import Tk,Label,Button
import rospy
from time import sleep
from PIL import Image, ImageTk


ws = Tk()
#ws.geometry('400x450+1000+300')
ws.title('Stopwatch')
ws.attributes('-fullscreen', True)
ws.config(bg='#efb570')
#ws.resizable(0,0)


ontym=8
offtym=5
ton=-1
linemode = 'dashed'
counter = 0
running = False

def counter_label(lbl):
    def count():
        if running:
            global counter,offtym,ontym,ton,linemode
            if counter == 0:             
                display="00"
            else:
                display='0' +str(counter)
                if counter > 9:
                   display = str(counter)

            lbl['text']=display    
            counter += 1
            ton += 1
            if ton > ontym:
               if linemode == 'dashed':
                   counter=0                   
                   lbl['text']='00'
                   sleep(offtym)

                   ton=-1                   
                   lbl.after(1000, count)
               else:                                            
                   lbl.after(1000, count)
            else:
               lbl.after(1000, count)

        
    count()     

def StartTimer(lbl):
    global running
    running=True
    counter_label(lbl)
    start_btn['state']='disabled'
    stop_btn['state']='normal'    

def StopTimer():
    global running
    start_btn['state']='normal'
    stop_btn['state']='disabled'   
    running = False



pic=Image.open("/home/nooduupachuu/catkin_ws/src/gui_sample/scripts/abc.png")
tkImg=ImageTk.PhotoImage(pic)
lbl1=Label(ws, image=tkImg, bg='#efb570')
lbl1.image=tkImg
lbl1.place(x=405, y=50)


lbl = Label(ws, text="00", fg="black", bg='#efb570', font="Verdana 80 bold")
label_msg = Label(ws, text="seconds", fg="black", bg='#efb570', font="Verdana 30 bold")
lbl.place(x=585, y=315)
label_msg.place(x=570, y=445)

start_btn=Button(ws, text='START', width=9, bd=2, font=("Arial Bold", 12), command=lambda:StartTimer(lbl))
stop_btn = Button(ws, text='STOP', width=9, bd=2, font=("Arial Bold", 12), state='disabled', command=StopTimer)
start_btn.place(x=535, y=700)
stop_btn.place(x=675, y=700)


ws.mainloop()

Tags: 代码textifwscountcounterplacerunning