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

0

I have the following code for a "timer", but it does not appear in the window, just in the Python 3.6 console. How do I get it printed in the window? (note: the window only opens when the preset time ends)

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()
    
asked by anonymous 07.05.2017 / 01:39

2 answers

0

You need to create a label in your window, after which you need to render and define the label update logic where the time will appear.

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()
    
07.05.2017 / 17:31
0

My response is similar to that of @ brow-joe, but as I tested it and it 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')       
    
07.05.2017 / 17:41