Halvurd
Halvurd

Reputation: 73

How to add timer with start/stop GUI in python

I've been googeling all day, tried loads of different ways, but I can't get this code to work. I want a simple timer that run a function when you press "Start", and stops when you press "Stop".

Example: When you press start, the function will print every second "Hello World", until you press stop.

My code with some comments so you can understand faster:

import sys
from Tkinter import *
from threading import Timer
# a boolean for telling the timer to stop
stop_timer = False

mgui = Tk()

def work(var):
    # stop_timers sets to True or False with Start/Stop
    stop_timer = var
    # work_done will evaluate if timer should start or be canceled
    def work_done(var2):
        stop_timer = var2
        # if stop was pressed t.start() will be ignored
        if stop_timer == False:
            t.start()
        # if stop was pressed timer will stop
        if stop_timer == True:
            print "Stopped!"
            t.cancel()
    t = Timer(1, work, [False])
    print "Something"
    work_done(var)

mgui.geometry('450x450')
mgui.title('Test')

cmd1 = lambda: work(False)
btn = Button(mgui, text="Start", command =cmd1).place(x=50, y=50)
cmd2 = lambda: work(True)
btn2 = Button(mgui, text="Stop", command =cmd2).place(x=100, y=50)

mgui.mainloop()

As you can tell, I'm new to this shizzle! Thanks, mates!

Upvotes: 2

Views: 4180

Answers (2)

Halvurd
Halvurd

Reputation: 73

By editing some in xndrme's post, I finally got it to work. Thank you!

I'll post the code here for possible future googlers.

import sys
from Tkinter import *
from threading import Timer

mgui = Tk()

def cmd2():
    global t
    if t:
        t.cancel()

def looper():
    global t
    t = Timer(1, looper)
    t.start()
    print "Hello World!"

mgui.geometry('450x450')
mgui.title('Test')

btn = Button(mgui, text="Start", command =looper).place(x=50, y=50)
btn2 = Button(mgui, text="Stop", command =cmd2).place(x=100, y=50)

mgui.mainloop()

Upvotes: 0

Alvaro Fuentes
Alvaro Fuentes

Reputation: 17485

This is a generic timer, you can also implement one in tkinter using after:

import time
import Tkinter as tk

import threading

class MyTimer(threading.Thread):

    def __init__(self, t):
        super(MyTimer,self).__init__()
        self.txt = t
        self.running = True

    def run(self):
        while self.running:
            self.txt['text'] = time.time()        


mgui = tk.Tk()
mgui.title('Test')

txt = tk.Label(mgui, text="time")
txt.grid(row=0,columnspan=2)

timer = None
def cmd1():
    global timer
    timer = MyTimer(txt)
    timer.start()
def cmd2():
    global timer
    if timer:
        timer.running = False
        timer= None

btn = tk.Button(mgui, text="Start", command =cmd1)
btn.grid(row=1,column=1)
btn2 = tk.Button(mgui, text="Stop", command =cmd2)
btn2.grid(row=1,column=2)

mgui.mainloop()

Upvotes: 2

Related Questions