how to make the time appear in the window(label)?

Asked

Viewed 328 times

0

I have the following "timer" code, but it does not appear in the window, only in the Python 3.6 console. How to make it be printed in the window? (Obs.: the window only opens when the preset time is over)

from tkinter import*
from datetime import datetime, timedelta
from sys import stdout
from time import sleep
janela = Tk()

segundos = int("3")#tempo que comeca 
tempo = timedelta(seconds=segundos)

while (str(tempo) >= "00:00:00"):
    stdout.write("\r%s" % tempo)
    tempo = tempo - timedelta(seconds=1)
    sleep(1)




janela.title("tempo")
janela["bg"] = "white"
janela.geometry("500x500")
janela.mainloop()
  • If the window only opens after the time runs out, how do you want to show the time in the window?

  • That’s what I want to know how to do!

2 answers

0


You need to create a label in your window, after this you need to render and set the update logic of the label where the time will be displayed.

using your code, I made some adaptations, see if it works:

import time
from tkinter import*
from datetime import datetime, timedelta
from sys import stdout

segundos = 3

class App():
    def __init__(self):
        self.janela = Tk()
        self.janela.title("tempo")
        self.janela.geometry("500x500")

        self.label = Label()
        self.tempo = timedelta(seconds=segundos)
        self.atualizarTemporizador()

        self.label.pack()
        self.janela.mainloop()

    def atualizarTemporizador(self):
        self.label.configure(text=self.tempo)
        if self.tempo > timedelta(seconds=0):
            self.tempo = self.tempo - timedelta(seconds=1)
            self.janela.after(1000, self.atualizarTemporizador)
            stdout.write("\r%s" % self.tempo)

app = App()

0

My answer is similar to @Brow-joe’s, but as I tested his and gave an error, I decided to put mine too (environment: Python 3.6):

import tkinter as tk
import time

class showtime():
    def __init__(self, t=30):
        self.ticker=t
        self.count = 0
        self.root = tk.Tk()
        self.label = tk.Label(text="00:00:00")
        self.label.pack()
        self.update_label()
        self.root.mainloop()

    def update_label (self):
        if self.count>=self.ticker:
            self.root.destroy()
            return
        else:
            self.count+=1
            now = time.strftime("%H:%M:%S")
            self.label.configure(text=now)
            self.root.after(1000, self.update_label)

app = showtime(10)        
print ('script terminado')       
  • What mistake did you make? I’m also using Python 3.6.0

  • I found kk, I changed the class name and forgot to change below, I edited the answer with the corrected code, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.