Home > Back-end >  tkinter .after() second and minute
tkinter .after() second and minute

Time:11-08

hey guys i have a problem im making a timer in tkinter but i cant use time.sleep() so i use .after() and i have new problem,I made an entry that I want the entry number to be * 60 and after the set time, a text will be written that says >> time is over! ,but then, how should that 60 be converted into seconds? my code:

from tkinter import * 
from playsound import playsound
from time import sleep
import time
def jik():
    a = int(text.get())
    app.after(a * 600)
    Label(app,text="time is over").pack()
app = Tk()
app.minsize(300,300)
app.maxsize(300,300)
text = Entry(app,font=20)
text.pack()
Button(app,text="start",command=jik).pack()
app.mainloop()

For example, if I press the number 1, it >>time is over in a fraction of a second

CodePudding user response:

The after command takes input in milliseconds, so multiply it by 1000 to convert it to seconds.

Additionally, I just made a small example that displays the countdown for you as the clock ticks down:

# Usually it is a good idea to refrain from importing everything from the tkinter
# package, as to not pollute your namespace
import tkinter as tk

root = tk.Tk()  # Customary to call your Tk object root
entry = tk.Entry(root)
entry.pack()

curtime = tk.Label(root)
curtime.pack()
is_running = False  # Global variable to ensure we can't run two timers at once


def countdown(count):
    global is_running
    if count > 0:
        curtime['text'] = f'{count:.2f}'  # Update label

        # Call the countdown function recursively until timer runs out
        root.after(50, countdown, count-0.05)  
    else:
        curtime['text'] = 'time is over'
        is_running = False


def btn_press():
    global is_running
    if is_running:
        return
    cnt = int(entry.get())
    is_running = True
    countdown(cnt)


tk.Button(root, text='start', command=btn_press).pack()
root.minsize(300, 300)
root.maxsize(300, 300)
root.mainloop()

CodePudding user response:

.after function takes two arguments, the first is the time in milliseconds, that is 1000 milliseconds is equal to one second, the second argument is a function to call after that time has passed, simply define what to do after the time has passed in a second function, and use it as a second argument as follows.

from tkinter import * 
from playsound import playsound
from time import sleep
import time

MILLISECOND_TO_SECOND = 1000
def jik():
    a = int(text.get())
    app.after(a * MILLISECOND_TO_SECOND, show_label)
    
def show_label():
    Label(app,text="time is over").pack()

app = Tk()
app.minsize(300,300)
app.maxsize(300,300)
text = Entry(app,font=20)
text.pack()
Button(app,text="start",command=jik).pack()
app.mainloop()
  • Related