Код на питоне секундомер

Stopwatch in Python

In Python you can use the time module to wait (you can also get the time and date). To be explicit, the time module provides various time-related functions. This is very useful for many applications. If you make a game, it should not update every millisecond. If you make weather station software, it makes no sense to update in such a short time. For an alarm clock app, you need it to wait. Lets say you want to make a stopwatch, without the program pausing there would be no way to create one.

Sleep function

The module time has a function named sleep, which pauses the program (it complete freezes the program).

This waits for t number of seconds. Consider this program which waits for one second before it outputs the next word.

import time.sleep print("Hello") time.sleep(1) print("World") 

Stopwatch

So you can use the time.sleep() function to pause the program. But a stopwatch doesn’t have a limit, it needs to go on. For that, you can use a while loop. Then you can use Ctrl+c to exit the program.

import time while True: print("Clock ticks") time.sleep(1) 
➜ ~ python3 stopwatch.py Clock ticks Clock ticks Clock ticks 

Until you press Ctrl+c. Now it needs to count seconds, you can use time.time() to get the current time. The example below will output every second passed until Ctrl+C is passed.

import time start = time.time() while True: time.sleep(1) total_secs = round(time.time() - start) print(total_secs) 

Formatting

To format it you can use f-strings with two digits. With a simple calculation you can get the minutes and seconds.

import time start = time.time() while True: time.sleep(1) total_secs = round(time.time() - start) minute = round(total_secs / 60) seconds = round(total_secs % 60) s = f"minute:02d>:seconds:02d>" print(s) 

Источник

How To Create A Stopwatch In Python

In this tutorial, we will be going through a fun program to create a stopwatch in python. For this, we will be using time.time() function from the time module.
A stopwatch essentially tells the time elapsed from start to stop.

time.time() in Python

We will be using time.time() function from the time module. Documentation is here.
time.time() function keeps the track of the number of seconds passed from the time the day began i.e. the epoch 00:00.
To use this function we will first import the time module into our code.

Time to create a stopwatch using Python

  1. We will import time module.
  2. The user will press Enter to start the stopwatch. At this point start_time is set using time.time(). So, at this point, start_time has the number of seconds passed since epoch when the clock is started.
  3. Now, the clock will run in the background.
  4. Now the user will press Enter again for stopping the stopwatch. At this point end_time is set using time.time(). So, at this point, end_time has the number of seconds passed since epoch when the clock is stopped.
  5. So, the time lapse can be calculated using the difference between end_time and start_time.
  6. time_lapsed has the value in seconds. We want the output in hours, minutes and seconds. To do this we will use the user-defined function time_convert().
  7. time_convert() will convert seconds into minutes by dividing the number of seconds by 60 and then the number of minutes divided by 60 is the number of hours.
  8. We are printing the Lapsed time also from inside time_convert().
import time def time_convert(sec): mins = sec // 60 sec = sec % 60 hours = mins // 60 mins = mins % 60 print("Time Lapsed = ::".format(int(hours),int(mins),sec)) input("Press Enter to start") start_time = time.time() input("Press Enter to stop") end_time = time.time() time_lapsed = end_time - start_time time_convert(time_lapsed)

Output

If 140 seconds have passed then the output will look like:

So, here it is. A very simple program to create a Stopwatch in Python.

10 responses to “How To Create A Stopwatch In Python”

Good day sir! Thankyou for this code you provided. It is very helpful.
But my problem here is that, I want to add a simple push button switch to turn on the stopwatch and then stop it again with it. But I dont know when to insert or even enter a code that will make the system work.

Hi Tyler, I was able to do so with this, but still working on it 🙂
Hope it helps while True:
start_time=time.time()
while True:
end_time=time.time()
print(stopTime-startTime)
time.sleep(.1)

Is there a way to save the times to view later? like when you open the program back up, it prints the last stopwatch times?

Yes There is, you can save the results into a file
Here is one of many ways how to do it: (It’ll work only on windows tho) import os
import time
exist = os.system(“if exist stopwatch.txt echo 1”)
if exist == “1”:
lastsec = os.system(“type stopwatch.txt”)
lastsec = int(lastsec)
os.system(“del stopwatch.txt”)
print(“Last stopwatch:”)
time_convert(lastsec) def time_convert(sec):
mins = sec // 60
sec = sec % 60
hours = mins // 60
mins = mins % 60
print(“Time Lapsed = ::”.format(int(hours),int(mins),sec))
input(“Press Enter to start”)
start_time = time.time()
input(“Press Enter to stop”)
end_time = time.time()
time_lapsed = end_time – start_time
save = time_lapsed
time_convert(time_lapsed)
os.system(“echo %d > stopwatch.txt” % (int(save)))

here is my solution: import tkinter as Tkinter
from datetime import datetime
import win32gui, win32con
the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE) running = False h = 0
m = 0
s = 0 def counter_label(label):
global counter, h, m, s
def count():
global counter, h, m, s
if running: s_h = h
s_m = m
s_s = s if h < 10:
s_h = «0» + str(h)
if m < 10:
s_m = «0» + str(m)
if s = 60:
s = 0
m += 1
if m >= 60:
m = 0
h += 1 count() def Start(label):
global running
running=True
counter_label(label)
start[‘state’]=’disabled’
stop[‘state’]=’normal’
reset[‘state’]=’normal’ def Stop():
global running
start[‘state’]=’normal’
stop[‘state’]=’disabled’
reset[‘state’]=’normal’
running = False def Reset(label):
global counter, h, m, s
h = 0
m = 0
s = 0
if running==False:
string = “Hours: 00”
string2 = “Minutes: 00”
string3 = “Seconds: 00”
display=(string)
display2=(string2)
display3=(string3) label[‘text’]=display
label2[‘text’]=display2
label3[‘text’]=display3 reset[‘state’]=’disabled’ root = Tkinter.Tk()
root.title(“Stopwatch”)
root.minsize(width=250, height=70) start_title1 = “””Hours: 00″”” start_title2 = “””Minutes: 00″”” start_title3 = “””Seconds: 00″”” label = Tkinter.Label(root, text=start_title1, fg=”black”, font=”Verdana 30 bold”, anchor=’w’)
label.pack(fill=’both’) label2 = Tkinter.Label(root, text=start_title2, fg=”black”, font=”Verdana 30 bold”, anchor=’w’)
label2.pack(fill=’both’) label3 = Tkinter.Label(root, text=start_title3, fg=”black”, font=”Verdana 30 bold”, anchor=’w’)
label3.pack(fill=’both’) f = Tkinter.Frame(root) start = Tkinter.Button(f, text=’Start’, width=6, command=lambda:Start(label))
stop = Tkinter.Button(f, text=’Stop’,width=6,state=’disabled’, command=Stop)
reset = Tkinter.Button(f, text=’Reset’,width=6, state=’disabled’, command=lambda:Reset(label))
f.pack(anchor = ‘center’,pady=5)
start.pack(side=”left”)
stop.pack(side =”left”)
reset.pack(side=”left”)
root.mainloop()

import time print(‘Press ENTER to begin, Press Ctrl + C to stop’)
while True:
try:
input() #For ENTER
starttime = time.time()
mins=0
hrs=0
while True:
secs = int(time.time()-starttime)
if secs == 60:
mins+=1
starttime = time.time()
if mins == 60:
hrs+=1
mins=0
print(hrs,”hrs:”,mins,”mins:”,secs,”:secs”)
time.sleep(1)
print(‘Started’)
except KeyboardInterrupt:
print(‘Stopped’)
endtime = time.time()
print(hrs,”hrs:”,mins,”mins:”,secs,”:secs”)
print(‘Total Time:’, round(endtime – starttime, 2),’secs’)
break

I am using the time.time( ) inside a while loop that don’t stop. But, I need the the time.time( ) to start all over whenever it enters the while loop again ?

Источник

Stopwatch Using Python Tkinter

Stopwatch Using Python Tkinter

We are all familiar with the stopwatch. And, it is possible to create a Stopwatch Using Python. According to our information, the DateTime module is already available in Python. We can use that module to create a timer in Python. We are hoping that this content will be fantastic. You can use this as a primary-level Python mini-project. Click here for the complete source code. Let’s get started.

Implementation for Stopwatch Using Python in Tkinter

Step1. Importing libraries and initializing variables

from tkinter import * import sys import time global count count =0

To make a timer in Python, we must first import the Tkinter package. To obtain a time, import the DateTime module. Declaring the count as global and setting it to zero.

Step 2. Stopwatch Class

class stopwatch(): def reset(self): global count count=1 self.t.set('00:00:00') 

In Python code, create a stopwatch class. Create a function to conduct a reset action after creating a class. This function resets the timing to 00:00:00, akin to restarting the stopwatch.

Step 3. Start method for Stopwatch Using Python

 def start(self): global count count=0 self.timer()

To start the stopwatch, write a function called start. This feature is useful for starting the stopwatch.

Step 4. Stop method

 def stop(self): global count count=1

To stop the stopwatch, we need a stop function. To conduct the stop operation in the stopwatch, we must write another function called to stop.

Step 5. Close method

 def close(self): self.root.destroy()

When creating applications, always include an exit button. That will make an excellent first impression on your application. To conduct the exit procedure, we must develop a function called close. When we click the exit button, it will exit the application.

Step 6. Create the timer method

 def timer(self): global count if(count==0): self.d = str(self.t.get()) h,m,s = map(int,self.d.split(":")) h = int(h) m=int(m) s= int(s) if(s<59): s+=1 elif(s==59): s=0 if(m<59): m+=1 elif(m==59): m=0 h+=1 if(h<10): h = str(0)+str(h) else: h= str(h) if(m<10): m = str(0)+str(m) else: m = str(m) if(s<10): s=str(0)+str(s) else: s=str(s) self.d=h+":"+m+":"+s self.t.set(self.d) if(count==0): self.root.after(1000,self.timer) 

Create a timer function to run the stopwatch. I hope you saw that I named a functioning self.timer(). So, when the program sees that sentence, it will call this function and do the task specified in the timer function.

Step 7. Creating the init method for Stopwatch Using Python

 def __init__(self): self.root=Tk() self.root.title("Stop Watch") self.root.geometry("600x200") self.t = StringVar() self.t.set("00:00:00") self.lb = Label(self.root,textvariable=self.t,font=("Times 40 bold"),bg="white") self.bt1 = Button(self.root,text="Start",command=self.start,font=("Times 12 bold"),bg=("#F88379")) self.bt2 = Button(self.root,text="Stop",command=self.stop,font=("Times 12 bold"),bg=("#F88379")) self.bt3 = Button(self.root,text="Reset",command=self.reset,font=("Times 12 bold"),bg=("#DE1738")) self.bt4 = Button(self.root, text="Exit", command=self.close,font=("Times 12 bold"),bg=("#DE1738")) self.lb.place(x=160,y=10) self.bt1.place(x=120,y=100) self.bt2.place(x=220,y=100) self.bt3.place(x=320,y=100) self.bt4.place(x=420,y=100) self.label = Label(self.root,text="",font=("Times 40 bold")) self.root.configure(bg='white') self.root.mainloop() a=stopwatch() 

Following that, we add an init function in this program, as well as a button for each operation. Furthermore, this function will invoke all of the functions. To improve our timer, we’re changing the backdrop colors of the letters.

Complete source code for Stopwatch using Python Tkinter

from tkinter import * import sys import time global count count =0 class stopwatch(): def reset(self): global count count=1 self.t.set('00:00:00') def start(self): global count count=0 self.timer() def stop(self): global count count=1 def close(self): self.root.destroy() def timer(self): global count if(count==0): self.d = str(self.t.get()) h,m,s = map(int,self.d.split(":")) h = int(h) m=int(m) s= int(s) if(s<59): s+=1 elif(s==59): s=0 if(m<59): m+=1 elif(m==59): m=0 h+=1 if(h<10): h = str(0)+str(h) else: h= str(h) if(m<10): m = str(0)+str(m) else: m = str(m) if(s<10): s=str(0)+str(s) else: s=str(s) self.d=h+":"+m+":"+s self.t.set(self.d) if(count==0): self.root.after(1000,self.timer) def __init__(self): self.root=Tk() self.root.title("Stop Watch") self.root.geometry("600x200") self.t = StringVar() self.t.set("00:00:00") self.lb = Label(self.root,textvariable=self.t,font=("Times 40 bold"),bg="white") self.bt1 = Button(self.root,text="Start",command=self.start,font=("Times 12 bold"),bg=("#F88379")) self.bt2 = Button(self.root,text="Stop",command=self.stop,font=("Times 12 bold"),bg=("#F88379")) self.bt3 = Button(self.root,text="Reset",command=self.reset,font=("Times 12 bold"),bg=("#DE1738")) self.bt4 = Button(self.root, text="Exit", command=self.close,font=("Times 12 bold"),bg=("#DE1738")) self.lb.place(x=160,y=10) self.bt1.place(x=120,y=100) self.bt2.place(x=220,y=100) self.bt3.place(x=320,y=100) self.bt4.place(x=420,y=100) self.label = Label(self.root,text="",font=("Times 40 bold")) self.root.configure(bg='white') self.root.mainloop() a=stopwatch()

Output:

output for Stopwatch Using Python Tkinter

In this tutorial, we learned how to create a Stopwatch Using Python Tkinter. This article will be useful for all Python beginners. Learn it completely. Try to solve the code on your own. If you have any questions, please leave them in the comment section.

  • Create your own ChatGPT with Python
  • SQLite | CRUD Operations in Python
  • Event Management System Project in Python
  • Ticket Booking and Management in Python
  • Hostel Management System Project in Python
  • Sales Management System Project in Python
  • Bank Management System Project in C++
  • Python Download File from URL | 4 Methods
  • Python Programming Examples | Fundamental Programs in Python
  • Spell Checker in Python
  • Portfolio Management System in Python
  • Stickman Game in Python
  • Contact Book project in Python
  • Loan Management System Project in Python
  • Cab Booking System in Python
  • Brick Breaker Game in Python
  • Tank game in Python
  • GUI Piano in Python
  • Ludo Game in Python
  • Rock Paper Scissors Game in Python
  • Snake and Ladder Game in Python
  • Puzzle Game in Python
  • Medical Store Management System Project in Python
  • Creating Dino Game in Python
  • Tic Tac Toe Game in Python
  • Test Typing Speed using Python App
  • Scientific Calculator in Python
  • GUI To-Do List App in Python Tkinter
  • Scientific Calculator in Python using Tkinter
  • GUI Chat Application in Python Tkinter

Источник

Читайте также:  All simple java programs
Оцените статью