ARW
ARW

Reputation: 61

StopWatch on Tkinter ...Creating a Class

I used this link as inspiration. My question is how I can rewrite this code into a class. I'm very new with classes and I'm trying to understand where I need to use (self) and where I don't through an example.

Stop Watch on Tkinter

root = Tkinter.Tk()
timeFrame = LabelFrame(root, text='Time Frame', width=1200)
timeFrame.grid(row=2,column=2, sticky=W)

timer = [0,0,0] # [minutes ,seconds, centiseconds]

def update_time():
    if (state):
        global timer
        timer[2] += 1

        if (timer[2] >= 100):   #100 centiseconds --> 1 second
            timer[2] = 0
            timer[1] += 1       #add 1 second

        if (timer[1] >= 60):    #60 seconds --> 1 minute
            timer[0] += 1
            timer[1] = 0

        timeString = str(timer[0]) + ':' + str(timer[1]) + ':' + str(timer[2])
        show.config(text=timeString)
    root.after(10, update_time)

def start():
    global state
    state = True
    print 'Clock Running...'

def pause():
    global state
    state = False
    timeString = str(timer[0]) + ':' + str(timer[1]) + ':' + str(timer[2])
    timeList.insert(END, timeString)
    print 'Clock Paused'    

def resetTime():
    global timer
    timer = [0,0,0]
    print 'Clock is Reset'  
    show.config(text='00:00:00')


state = False

resetButton = Button(timeFrame, text='Reset', command=resetTime)
resetButton.grid(row=2,column=1)

pauseButton = Button(timeFrame, text='Pause', command=pause)
pauseButton.grid(row=1,column=1)

startButton = Button(timeFrame, text='Start', command=start)
startButton.grid(row=0,column=1)

show = Label(timeFrame, text='00:00:00', font=('Helvetica', 30))
show.grid(row=0, column=0)

timeList = Listbox(timeFrame, yscrollcommand = scrollbar.set)
timeList.grid(row=1, column=0, rowspan=3)

# Quit Button
quit = Button(timeFrame, text='QUIT', command=quit)
quit.grid(row=3, column=1)
update_time()

root.mainloop()

The code above works with a "small heartbeat" on python 3.5.0 Can anyone help me understand how to translate this code into a class??

Here is my best try at doing what I want:

Error: Stopwatch instance has no attribute 'running' - Line 48

import Tkinter
from Tkinter import *

root = Tkinter.Tk()

# running = False

class Stopwatch(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.grid()
        self.widgets()
        self.update_time()
        self.running = False
        self.update_time()
        self.timer = [0,0,0]    # [minutes ,seconds, centiseconds]
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])

    def widgets(self):
        self.timeFrame = LabelFrame(root, text='Time Frame', width=1200)
        self.timeFrame.grid(row=0,column=0, sticky=W)

        self.resetButton = Button(self.timeFrame, text='Reset', command=self.resetTime)
        self.resetButton.grid(row=2,column=1)

        self.pauseButton = Button(self.timeFrame, text='Pause', command=self.pause)
        self.pauseButton.grid(row=1,column=1)

        self.startButton = Button(self.timeFrame, text='Start', command=self.start)
        self.startButton.grid(row=0,column=1)

        self.show = Label(self.timeFrame, text='00:00:00', font=('Helvetica', 30))
        self.show.grid(row=0, column=0)

        # Quit Button
        self.quit = Button(self.timeFrame, text='QUIT', command=self.quit)
        self.quit.grid(row=3, column=1)


    def update_time(self):

        if (self.running == True):      #Clock is running

            self.timer[2] += 1

            if (self.timer[2] >= 100):  #100 centiseconds --> 1 second
                self.timer[2] = 0
                self.timer[1] += 1      #add 1 second

            if (self.timer[1] >= 60):   #60 seconds --> 1 minute
                self.timer[0] += 1
                self.timer[1] = 0

            self.timeString = str(timer[0]) + ':' + str(timer[1]) + ':' + str(timer[2])
            self.show.config(text=timeString)
        root.after(10, update_time)


    def start(self):            #Start the clock
        global running
        running = True
        print 'Clock Running...'

    def pause(self):            #Pause the clock
        global running
        running = False
        print 'Clock Paused'    

    def resetTime(self):        #Reset the clock
        global timer
        running = False
        self.timer = [0,0,0]
        print 'Clock is Reset'  
        self.show.config(text='00:00:00')

    def quit(self):             #Quit the program
        root.destroy()



watch = Stopwatch(root)

root.mainloop()

Ok, here is my fixed Stopwatch program...This one works

import random
import math
import turtle
import time
import Tkinter
from Tkinter import *

root = Tkinter.Tk()

# running = False

class Stopwatch(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.grid()
        self.widgets()
        self.running = False
        self.timer = [0,0,0]    # [minutes ,seconds, centiseconds]
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
        self.update_time()

    def widgets(self):
        self.timeFrame = LabelFrame(root, text='Time Frame', width=1200)
        self.timeFrame.grid(row=0,column=0, sticky=W)

        self.resetButton = Button(self.timeFrame, text='Reset', command=self.resetTime)
        self.resetButton.grid(row=2,column=1)

        self.pauseButton = Button(self.timeFrame, text='Pause', command=self.pause)
        self.pauseButton.grid(row=1,column=1)

        self.startButton = Button(self.timeFrame, text='Start', command=self.start)
        self.startButton.grid(row=0,column=1)

        self.show = Label(self.timeFrame, text='00:00:00', font=('Helvetica', 30))
        self.show.grid(row=0, column=0)

        # Quit Button
        self.quit = Button(self.timeFrame, text='QUIT', command=self.quit)
        self.quit.grid(row=3, column=1)


    def update_time(self):

        if (self.running == True):      #Clock is running

            self.timer[2] += 1

            if (self.timer[2] >= 100):  #100 centiseconds --> 1 second
                self.timer[2] = 0
                self.timer[1] += 1      #add 1 second

            if (self.timer[1] >= 60):   #60 seconds --> 1 minute
                self.timer[0] += 1
                self.timer[1] = 0

            self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
            self.show.config(text=self.timeString)
        root.after(10, self.update_time)


    def start(self):            #Start the clock
        self.running = True
        print 'Clock Running...'

    def pause(self):            #Pause the clock
        self.running = False
        print 'Clock Paused'    

    def resetTime(self):        #Reset the clock
        self.running = False
        self.timer = [0,0,0]
        print 'Clock is Reset'  
        self.show.config(text='00:00:00')

    def quit(self):             #Quit the program
        root.destroy()



watch = Stopwatch(root)

root.mainloop()

Upvotes: 0

Views: 1516

Answers (2)

ARW
ARW

Reputation: 61

This is the final product...it contains a stopwatch (counts up) and timer (counts down).

import Tkinter
from Tkinter import *


# This program is designed to count up from zero
class CountsUp(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.grid()
        self.widgets()
        self.running = False
        self.timer = [0,0,0]    # [minutes ,seconds, centiseconds]
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
        self.update_time()

    def widgets(self):
        self.timeFrame = LabelFrame(root, text='Counts Up')
        self.timeFrame.grid(row=0,column=0, sticky=W)

        self.resetButton = Button(self.timeFrame, text='Reset', command=self.resetTime)
        self.resetButton.grid(row=2,column=1)

        self.pauseButton = Button(self.timeFrame, text='Pause', command=self.pause)
        self.pauseButton.grid(row=1,column=1)

        self.startButton = Button(self.timeFrame, text='Start', command=self.start)
        self.startButton.grid(row=0,column=1)

        self.show = Label(self.timeFrame, text='00:00:00', font=('Helvetica', 30))
        self.show.grid(row=0, column=0)

        self.quit = Button(self.timeFrame, text='QUIT', command=self.quit)
        self.quit.grid(row=3, column=1)


    def update_time(self):

        if (self.running == True):      #Clock is running

            self.timer[2] += 1          #Count Down

            if (self.timer[2] >= 100):  #100 centiseconds --> 1 second
                self.timer[2] = 0       #reset to zero centiseconds
                self.timer[1] += 1      #add 1 second

            if (self.timer[1] >= 60):   #60 seconds --> 1 minute
                self.timer[0] += 1      #add 1 minute
                self.timer[1] = 0       #reset to 0 seconds

            self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
            self.show.config(text=self.timeString)
        root.after(10, self.update_time)

    def start(self):            #Start the clock
        self.running = True
        print 'Clock Running...'

    def pause(self):            #Pause the clock
        self.running = False
        print 'Clock Paused'    

    def resetTime(self):        #Reset the clock
        self.running = False
        self.timer = [0,0,0]
        print 'Clock is Reset'  
        self.show.config(text='00:00:00')

    def quit(self):             #Quit the program
        root.destroy()



# This program is designed to count down from a starting time
class CountsDown(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.grid()
        self.widgets()
        self.running = False
        self.timer = [0,0,0]    # [minutes ,seconds, centiseconds]
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
        self.update_time()

    def widgets(self):
        self.timeFrame = LabelFrame(root, text='Counts Down')
        self.timeFrame.grid(row=2,column=0, sticky=W)

        self.resetButton = Button(self.timeFrame, text='Reset', command=self.resetTime)
        self.resetButton.grid(row=2,column=1)

        self.pauseButton = Button(self.timeFrame, text='Pause', command=self.pause)
        self.pauseButton.grid(row=1,column=1)

        self.startButton = Button(self.timeFrame, text='Start', command=self.start)
        self.startButton.grid(row=0,column=1)

        self.show = Label(self.timeFrame, text='00:00:00', font=('Helvetica', 30))
        self.show.grid(row=0, column=0)

        self.addMinute = Button(self.timeFrame, text='Add Minute', command=self.addMinute)
        self.addMinute.grid(row=2,column=0)

        self.addSecond = Button(self.timeFrame, text='Add Second', command=self.addSecond)
        self.addSecond.grid(row=3,column=0)

        self.quit = Button(self.timeFrame, text='QUIT', command=self.quit)
        self.quit.grid(row=3, column=1)


    def update_time(self):

        if (self.running == True):      #Clock is running

            self.timer[2] -= 1          #Count Down

            if (self.timer[2] < 0):     #if centiseconds is negative
                self.timer[2] = 100     #reset to 100 centiseconds
                self.timer[1] -= 1      #subtract 1 second

            if (self.timer[1] < 0):     #if seconds is negative
                self.timer[1] = 60      #reset to 60 seconds
                self.timer[1] -= 1      #subtract 1 second
                self.timer[0] -= 1      #subtract 1 minute

            self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
            self.show.config(text=self.timeString)
        root.after(10, self.update_time)



    def addMinute(self):
        self.timer[0] += 1
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
        self.show.config(text=self.timeString)

    def addSecond(self):
        self.timer[1] += 1
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
        self.show.config(text=self.timeString)

    def start(self):            #Start the clock
        self.running = True
        print 'Clock Running...'

    def pause(self):            #Pause the clock
        self.running = False
        print 'Clock Paused'    

    def resetTime(self):        #Reset the clock
        self.running = False
        self.timer = [0,0,0]
        print 'Clock is Reset'  
        self.show.config(text='00:00:00')

    def quit(self):             #Quit the program
        root.destroy()



root = Tkinter.Tk()

up = CountsUp(root)
down = CountsDown(root)

root.mainloop()

Upvotes: 1

Jozef M&#233;ry
Jozef M&#233;ry

Reputation: 357

There are multiple ways of doing it. I'll show you my preffered version

from tkinter import * #if below 3.X it's Tkinter


class Anynameyoulike(Tk): #passing Tk to the class directly, makes most sense for me
    def __init__(self): #__init__ is a special method thats get called automatically,
        Tk.__init__(self) #whenever you create an object out of this class
        #use init to make variables and call certain methods like creating UI 
        self.timer = [0,0,0] # [minutes ,seconds, centiseconds]
        #don't forget the self., so you the whole class knows this object   
        self.resizeable(0, 0) #make it resizeable to 0 pixels in width and height aka. not resizeable is what I like to do   
        self.makeui()
    def makeui(self):
        timeFrame = LabelFrame(root, text='Time Frame', width=1200)
        timeFrame.grid(row=2,column=2, sticky=W)
        #also rest of the buttons, labels I didn't bother copying
        #so on
    def start(self): #don't forget to pass in self
        global state #define it like self.state in init and no need for global
        state = True
        print 'Clock Running...'
   #define rest of the stuff needed copy/paste, adjust the object names, easy

#to finish do
anyname = Anynameyoulike()
anyname.mainloop() 

Upvotes: 0

Related Questions