0

I'm trying to make a tkinter widget that will actively update. Please note, countdown() is called first!! My problem is that once I enter duration into countdown, it closes the old widget as it should(not seen here). However, the new widget, that has the countdown timer in it, does not even appear. If I hit stop in my IDE, the widget does pop up, with how much time was left when the process was stopped.

def update(start, finish):
    timeRemaining = finish - start
    timeDisplay = Label(text = "%s" % timeRemaining)
    timeDisplay.pack(side = BOTTOM)
    while True:
        #check = timeRemaining.timetuple()
        timeRemaining = str(finish - datetime.datetime.now())
        timeDisplay.config(text=timeRemaining)
        timeDisplay.pack()
        time.sleep(.01)


def countdown(duration):
    root.destroy()
    title = Label(text = "Countdown")
    title.pack()
    duration = float(duration)
    print(duration)
    start = datetime.datetime.now()
    startHours =  int(duration / 60)
    startMinutes = int(duration % 60)
    startSeconds = (((duration%60) - startMinutes)*60)
    finish = start + datetime.timedelta(hours = startHours, minutes = startMinutes, seconds = startSeconds)
    update(start, finish)

I hope I gave enough information. If there's something in here that doesn't make sense without context, let me know.

Any ideas? Thanks.

spurrkins
  • 126
  • 2
  • 11
  • http://stackoverflow.com/questions/2400262/code-a-timer-in-a-python-gui-in-tkinter – Joran Beasley Jun 27 '14 at 23:16
  • I actually did see that already while I was searching for help, but I thought that a while loop with a sleep function in each iteration would work the same. Is that the only way something like this will work? – spurrkins Jun 27 '14 at 23:23
  • yes ... because you dont allow it any time to update in your loop you need to hand control back to the main tk loop – Joran Beasley Jun 27 '14 at 23:28

1 Answers1

2

I modified this How to create a timer using tkinter? to do basically what you want

# for python 3.x use 'tkinter' rather than 'Tkinter'
import Tkinter as tk
import datetime
import math
MINUTE = 60
HOUR = 60*MINUTE
class App():
    def __init__(self):
        self.root = tk.Tk()
        self.done_time=datetime.datetime.now() + datetime.timedelta(seconds=HOUR/2) # half hour
        self.label = tk.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop()

    def update_clock(self):
        elapsed = self.done_time - datetime.datetime.now()
        h,m,s,fractional_s = elapsed.seconds/3600,elapsed.seconds/60,elapsed.seconds%60
        fractional_seconds = math.floor(elapsed.microseconds/1000000.0*100)
        self.label.configure(text="%02d:%02d:%02d.%02d"%(h,m,s))
        self.root.after(1000, self.update_clock)

app=App()

(I put fractional_seconds just in case you needed them ...)

Community
  • 1
  • 1
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179