Affichage des articles dont le libellé est chronometer. Afficher tous les articles
Affichage des articles dont le libellé est chronometer. Afficher tous les articles

Create a Stopwatch Using Python Tkinter

How to Create a Modern Python Stopwatch with Tkinter GUI: A Step-by-Step Tutorial




In this Python tutorial we will create a simple stopwatch application using the Tkinter library for the graphical user interface. 
The stopwatch has a timer display, a start/stop button, and a reset button. 
Users can start, stop, and reset the timer, which displays the elapsed time in hours, minutes, seconds, and milliseconds.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:



import tkinter as tk
from tkinter import ttk
import time


class StopWatch(tk.Tk):

def __init__(self):

super().__init__()
self.title("Stop Watch")
self.geometry("300x150")
self.configure(bg="#3498db")

# Initialize variables
self.time_elapsed = 0
self.is_running = False

# Label for displaying time
self.label_timer = ttk.Label(self, text = "00:00:00:000", font=('Arial', 24),
        anchor="center", foreground="white", background="#3498db")
self.label_timer.pack(pady=20)

# Start/Stop button
self.button_start_stop = ttk.Button(self, text="Start",
        command=self.start_stop, style="TButton")

self.button_start_stop.pack(side = tk.LEFT, padx = 10)

# Reset button
self.button_reset = ttk.Button(self, text="Reset",
        command=self.reset, style="TButton")

self.button_reset.pack(side = tk.RIGHT, padx = 10)

# Configure button style
self.style = ttk.Style()
self.style.configure("TButton", padding=7, font=("Helvatica", 12))

# Initialize the stopwatch
self.update_time()


def start_stop(self):
# Toggle start/stop functionality
if self.is_running:
self.is_running = False
self.button_start_stop.config(text="Start")
else:
self.is_running = True
self.button_start_stop.config(text="Stop")
self.start_time = time.time() - self.time_elapsed
self.update_time()



def reset(self):
# Reset the stopwatch
self.is_running = False
self.time_elapsed = 0
self.label_timer.config(text="00:00:00:000")
self.button_start_stop.config(text="Start")

def update_time(self):
# Update the displayed time
if self.is_running:
elapsed_time = time.time() - self.start_time
self.time_elapsed = elapsed_time
else:
elapsed_time = self.time_elapsed

# Calculate hours, minutes, seconds, and milliseconds
hours = int(elapsed_time / 3600)
minutes = int((elapsed_time % 3600) / 60)
seconds = int(elapsed_time % 60)
milliseconds = int((elapsed_time % 1) * 1000)

# Format the time string
time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}:{milliseconds:03d}"

# Update the label text
self.label_timer.config(text=time_str)

# Schedule the update after 10 milliseconds
self.after(10, self.update_time)



if __name__ == "__main__":

app = StopWatch()
app.mainloop()


The Final Result:








Java - Create Stopwatch App

How to Create a Chronometer App in Java NetBeans

How to Create a Chronometer App in Java NetBeans


In this Java Tutorial we will see How To Make a graphical user interface for a chronometer application In Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Create a window that display time in the format "HH:mm:ss.SSS" (hours, minutes, seconds, and milliseconds).
- When the "Start" button is clicked, the chronometer starts measuring time.
- Conversely, when the "Stop" button is clicked, the chronometer stops measuring time.





Project Source Code:




package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.Dictionary;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;


public class ChronometerApp extends JFrame {

    private JLabel timeLabel;
    private JButton startButton;
    private JButton stopButton;
    private Timer timer;
    private long startTimer;
    private boolean isRunning;
    
    public ChronometerApp(){
        setTitle("Chronometer App");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 200);
        setLocationRelativeTo(null);
        setResizable(false);
        initialize(); // initialize the user interface
        setVisible(true);
    }
    
    private void initialize(){
        
        // Create and configure the time display label
        timeLabel = new JLabel("00:00:00.000");
        timeLabel.setFont(new Font("Arial", Font.BOLD, 48));
        timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        
        // Create and configure the Start button
        startButton = new JButton("Start");
        startButton.setFont(new Font("Arial", Font.PLAIN, 16));
        startButton.setBackground(new Color(63, 81, 181));
        startButton.setForeground(Color.white);
        startButton.setFocusPainted(false);
        startButton.setBorderPainted(false);
        
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
               start(); // Start the chronometer
            
            }
        });
        
        // Create and configure the Stop button
        stopButton = new JButton("Stop");
        stopButton.setFont(new Font("Arial", Font.PLAIN, 16));
        stopButton.setBackground(new Color(244, 67, 54));
        stopButton.setForeground(Color.white);
        stopButton.setEnabled(false);
        stopButton.setFocusPainted(false);
        stopButton.setBorderPainted(false);
        
        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
               stop(); // Stop the chronometer
            
            }
        });
        
        // Create a panel for the buttons and arrange them horizontally
        JPanel buttonPanel = new JPanel();
        buttonPanel.setBackground(Color.white);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,0,10,0));
        buttonPanel.add(startButton);
        buttonPanel.add(Box.createRigidArea(new Dimension(20, 0)));
        buttonPanel.add(stopButton);
        
        // Set up the layout and add components to the content pane
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(timeLabel, BorderLayout.CENTER);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        
        // Create a timer to update the chronometer display every 10 milliseconds
        timer = new Timer(10, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
                updateTimer(); // Update the chronometer display
            
            }
        });
        
    }
    
    private void start(){
    
        if(!isRunning){
            startTimer = System.currentTimeMillis();
            timer.start(); // start the timer
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            isRunning = true;
        }
        
    }
    
    private void stop(){
    
        if(isRunning){
            timer.stop(); // stop the timer
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            isRunning = false;
        }
        
    }
    
    private void updateTimer(){
    
        long currentTime = System.currentTimeMillis();
        long elapsedTime = currentTime - startTimer;
        
        // Calculate hours, minutes, seconds, and milliseconds
        long hours = elapsedTime / 3600000;
        long minutes = (elapsedTime % 3600000) / 60000;
        long seconds = (elapsedTime % 60000) / 1000;
        long milliseconds = elapsedTime % 1000;
        
        // Format the time components as strings with leading zeros if needed
        DecimalFormat format = new DecimalFormat("00");
        String timeString = format.format(hours)+":"
                            +format.format(minutes)+":"
                            +format.format(seconds)+"."
                            +format.format(milliseconds);
        
        // Update the time label with the formatted time
        timeLabel.setText(timeString);
        
    }
    
    
    public static void main(String[] args){
        
        SwingUtilities.invokeLater(() -> {
        
            new ChronometerApp();
        
        });
        
        
    }
    
    
}


The Final Result:



Java Stopwatch Project Tutorial

Chronometer App in Java NetBeans