473,465 Members | 1,920 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

If I want to add a timer to my program (Timed practice exam)

Jory R Ferrell
62 New Member
I will be using python 3 (comp is currently broken so I can't test examples) btw. Do I need to create the timer function as a separate thread and create a event-driven interruption in the main loop which reacts to the timer? Or is there a simpler way to create the timer INSIDE the main loop that I'm too retarded to think of? :P
Jan 13 '12 #1

✓ answered by bvdet

The user can interact with other widgets while the timer runs. Example:

Expand|Select|Wrap|Line Numbers
  1. import Tkinter
  2. from Tkconstants import *
  3. import time
  4.  
  5. textFont1 = ("Arial", 16, "bold")
  6.  
  7. class EntryWidget(Tkinter.Entry):
  8.     def __init__(self, master, initial=""):
  9.         Tkinter.Entry.__init__(self, master=master)
  10.         self.value = Tkinter.StringVar()
  11.         self.config(textvariable=self.value, width=20,
  12.                     relief="ridge", font=textFont1,
  13.                     bg="#ddd", fg="#e00",
  14.                     justify='center')
  15.         self.pack(fill=BOTH, expand=1)
  16.         self.value.set(initial)
  17.  
  18. class Timer(Tkinter.Frame):
  19.     def __init__(self, master):
  20.         self.master = master
  21.         buttonFrame = Tkinter.Frame(master)
  22.         self.btnList = []
  23.         for i, name in enumerate(["Start", "Stop", "Exit"]):
  24.             def handler(i=i):
  25.                 return self.manage_timer(i)
  26.             btn = Tkinter.Button(buttonFrame, text=name, padx=5, pady=5,
  27.                          bd=4, bg='#ff0', fg="#00f",
  28.                          activebackground = "#00f",
  29.                          activeforeground = "#ff0",
  30.                          font=textFont1,
  31.                          relief='raised',
  32.                          command=handler)
  33.             btn.pack(side="left", fill=BOTH, expand=1)
  34.             self.btnList.append(btn)
  35.         buttonFrame.pack(fill=BOTH, expand=1)
  36.         self.start()
  37.  
  38.     def start(self):
  39.         Tkinter.Frame.__init__(self, self.master)
  40.         self.pack(fill=BOTH, expand=1)
  41.         self.clockVar = Tkinter.StringVar(self.master)
  42.         self.clockLabel = Tkinter.Label(self, textvariable=self.clockVar,
  43.                                         relief="raised", font=textFont1,
  44.                                         bd=3,
  45.                                         bg='#ffffff000',
  46.                                         fg="#000000fff",
  47.                                         activebackground = "#000000fff",
  48.                                         activeforeground = "#ffffff000",
  49.                                         takefocus=1,
  50.                                         padx=3,
  51.                                         pady=3,
  52.                                         width=20)
  53.         self.clockLabel.pack(fill=BOTH, expand=1)
  54.         self.clockVar.set("0.000")
  55.         self.btnList[1].configure(state=DISABLED)
  56.         self.w = EntryWidget(self, "Enter Text")
  57.         self.w.bind(sequence="<KeyRelease>", func=self.lower)
  58.  
  59.     def lower(self, event):
  60.         event.widget.value.set(event.widget.value.get().lower())
  61.  
  62.     def update_time(self):
  63.         self.clockVar.set("%0.3f" % (time.time()-self.starttime))
  64.         if self.active:
  65.             self.after(10, self.update_time)
  66.         else:
  67.             self.clockVar.set("Elapsed time: %0.3f"% (time.time()-self.starttime))
  68.  
  69.     def manage_timer(self, idx):
  70.         if idx == 0:
  71.             self.btnList[0].configure(state=DISABLED)
  72.             self.btnList[1].configure(state=NORMAL)
  73.             self.active = True
  74.             self.starttime = time.time()
  75.             self.update_time()
  76.         elif idx == 1:
  77.             self.btnList[0].configure(state=NORMAL)
  78.             self.btnList[1].configure(state=DISABLED)
  79.             self.active = False
  80.         elif idx == 2:
  81.             self.master.destroy()
  82.  
  83. if __name__ == "__main__":
  84.     root = Tkinter.Tk()
  85.     app = Timer(root)
  86.     root.mainloop()

5 2148
Jory R Ferrell
62 New Member
Nvrmind....answered my own question.
Jan 13 '12 #2
bvdet
2,851 Recognized Expert Moderator Specialist
I just happen to have a Tkinter script demonstrating a timer application. You should be able to do what you want in the main loop.
Expand|Select|Wrap|Line Numbers
  1. import Tkinter
  2. from Tkconstants import *
  3. import time
  4.  
  5. textFont1 = ("Arial", 16, "bold")
  6.  
  7. class Timer(Tkinter.Frame):
  8.     def __init__(self, master):
  9.         self.master = master
  10.         buttonFrame = Tkinter.Frame(master)
  11.         self.btnList = []
  12.         for i, name in enumerate(["Start", "Stop", "Exit"]):
  13.             def handler(i=i):
  14.                 return self.manage_timer(i)
  15.             btn = Tkinter.Button(buttonFrame, text=name, padx=5, pady=5,
  16.                          bd=4, bg='#ff0', fg="#00f",
  17.                          activebackground = "#00f",
  18.                          activeforeground = "#ff0",
  19.                          font=textFont1,
  20.                          relief='raised',
  21.                          command=handler)
  22.             btn.pack(side="left", fill=BOTH, expand=1)
  23.             self.btnList.append(btn)
  24.         buttonFrame.pack(fill=BOTH, expand=1)
  25.         self.start()
  26.  
  27.     def start(self):
  28.         Tkinter.Frame.__init__(self, self.master)
  29.         self.pack(fill=BOTH, expand=1)
  30.         self.clockVar = Tkinter.StringVar(self.master)
  31.         self.clockLabel = Tkinter.Label(self, textvariable=self.clockVar,
  32.                                         relief="raised", font=textFont1,
  33.                                         bd=3,
  34.                                         bg='#ffffff000',
  35.                                         fg="#000000fff",
  36.                                         activebackground = "#000000fff",
  37.                                         activeforeground = "#ffffff000",
  38.                                         takefocus=1,
  39.                                         padx=3,
  40.                                         pady=3,
  41.                                         width=16)
  42.         self.clockLabel.pack(fill=BOTH, expand=1)
  43.         self.clockVar.set("0.000")
  44.         self.btnList[1].configure(state=DISABLED)
  45.  
  46.     def update_time(self):
  47.         self.clockVar.set("%0.3f" % (time.time()-self.starttime))
  48.         if self.active:
  49.             self.after(10, self.update_time)
  50.         else:
  51.             self.clockVar.set("Elapsed time: %0.3f"% (time.time()-self.starttime))
  52.  
  53.     def manage_timer(self, idx):
  54.         if idx == 0:
  55.             self.btnList[0].configure(state=DISABLED)
  56.             self.btnList[1].configure(state=NORMAL)
  57.             self.active = True
  58.             self.starttime = time.time()
  59.             self.update_time()
  60.         elif idx == 1:
  61.             self.btnList[0].configure(state=NORMAL)
  62.             self.btnList[1].configure(state=DISABLED)
  63.             self.active = False
  64.         elif idx == 2:
  65.             self.master.destroy()
  66.  
  67. if __name__ == "__main__":
  68.     root = Tkinter.Tk()
  69.     app = Timer(root)
  70.     root.mainloop()
Jan 13 '12 #3
bvdet
2,851 Recognized Expert Moderator Specialist
OK Jory - What was the answer?
Jan 13 '12 #4
Jory R Ferrell
62 New Member
:P Well...it was the wrong answer....I thought I would need to use a thread! So since the timer is created as an instance of an object instead of just as a function, it allows me to run the timer at the same time as determining questions to ask and taking input from the user, as if I was using a separate thread?
Jan 13 '12 #5
bvdet
2,851 Recognized Expert Moderator Specialist
The user can interact with other widgets while the timer runs. Example:

Expand|Select|Wrap|Line Numbers
  1. import Tkinter
  2. from Tkconstants import *
  3. import time
  4.  
  5. textFont1 = ("Arial", 16, "bold")
  6.  
  7. class EntryWidget(Tkinter.Entry):
  8.     def __init__(self, master, initial=""):
  9.         Tkinter.Entry.__init__(self, master=master)
  10.         self.value = Tkinter.StringVar()
  11.         self.config(textvariable=self.value, width=20,
  12.                     relief="ridge", font=textFont1,
  13.                     bg="#ddd", fg="#e00",
  14.                     justify='center')
  15.         self.pack(fill=BOTH, expand=1)
  16.         self.value.set(initial)
  17.  
  18. class Timer(Tkinter.Frame):
  19.     def __init__(self, master):
  20.         self.master = master
  21.         buttonFrame = Tkinter.Frame(master)
  22.         self.btnList = []
  23.         for i, name in enumerate(["Start", "Stop", "Exit"]):
  24.             def handler(i=i):
  25.                 return self.manage_timer(i)
  26.             btn = Tkinter.Button(buttonFrame, text=name, padx=5, pady=5,
  27.                          bd=4, bg='#ff0', fg="#00f",
  28.                          activebackground = "#00f",
  29.                          activeforeground = "#ff0",
  30.                          font=textFont1,
  31.                          relief='raised',
  32.                          command=handler)
  33.             btn.pack(side="left", fill=BOTH, expand=1)
  34.             self.btnList.append(btn)
  35.         buttonFrame.pack(fill=BOTH, expand=1)
  36.         self.start()
  37.  
  38.     def start(self):
  39.         Tkinter.Frame.__init__(self, self.master)
  40.         self.pack(fill=BOTH, expand=1)
  41.         self.clockVar = Tkinter.StringVar(self.master)
  42.         self.clockLabel = Tkinter.Label(self, textvariable=self.clockVar,
  43.                                         relief="raised", font=textFont1,
  44.                                         bd=3,
  45.                                         bg='#ffffff000',
  46.                                         fg="#000000fff",
  47.                                         activebackground = "#000000fff",
  48.                                         activeforeground = "#ffffff000",
  49.                                         takefocus=1,
  50.                                         padx=3,
  51.                                         pady=3,
  52.                                         width=20)
  53.         self.clockLabel.pack(fill=BOTH, expand=1)
  54.         self.clockVar.set("0.000")
  55.         self.btnList[1].configure(state=DISABLED)
  56.         self.w = EntryWidget(self, "Enter Text")
  57.         self.w.bind(sequence="<KeyRelease>", func=self.lower)
  58.  
  59.     def lower(self, event):
  60.         event.widget.value.set(event.widget.value.get().lower())
  61.  
  62.     def update_time(self):
  63.         self.clockVar.set("%0.3f" % (time.time()-self.starttime))
  64.         if self.active:
  65.             self.after(10, self.update_time)
  66.         else:
  67.             self.clockVar.set("Elapsed time: %0.3f"% (time.time()-self.starttime))
  68.  
  69.     def manage_timer(self, idx):
  70.         if idx == 0:
  71.             self.btnList[0].configure(state=DISABLED)
  72.             self.btnList[1].configure(state=NORMAL)
  73.             self.active = True
  74.             self.starttime = time.time()
  75.             self.update_time()
  76.         elif idx == 1:
  77.             self.btnList[0].configure(state=NORMAL)
  78.             self.btnList[1].configure(state=DISABLED)
  79.             self.active = False
  80.         elif idx == 2:
  81.             self.master.destroy()
  82.  
  83. if __name__ == "__main__":
  84.     root = Tkinter.Tk()
  85.     app = Timer(root)
  86.     root.mainloop()
Jan 13 '12 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: John Salerno | last post by:
Ok, I made some changes and want to see what you guys think, as far as syntax and logic, etc. What I want it to do is show the number of minutes remaining each minute, and then beep at the end. Is...
29
by: Mr Newbie | last post by:
Im going to be looking to do this exam fairly soon, but ive done a couple of practice tests and found them to be a bit tricky in as much as you have to REALLY READ the questions carefully else they...
3
by: rojavenkat81 | last post by:
Hi All, Please help me regarding php program for convert video file to .flv file. I searched in many sites but i got only tool to convert video file to .flv file.But I want convert...
8
by: Nirav Amin | last post by:
Create a 2-D array containing the data : Pakistan Sweden France Iran China Japan Russia China Italy China China ...
6
by: John | last post by:
Hello, I'm brand new to Javascript and would like to know what is the best program that I can use to learn JavaScript. I would like something with syntax highlighting if possible. Any help...
8
by: mrcw | last post by:
I'm trying to make a timer which is a reusable module. Is this possible? I would like to pass 1 argument to the timer. The argument is the delay that the main program waits before it continues. ...
3
by: Colt | last post by:
I have this program that an associate will input their ID# then it prints back saying (your associate ID# is XXX) then it will state what time it they clocked in/out--Ex: Your ID# is 101 and you left...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.