0

I previously made a stopwatch program using tkinter, later realising tkinter is trash, so i have moved on to using PyQt5 but i am having some trouble. Upon booting up, everything is displayed correctly, but when i press start or reset, the program crashes. Something to do with threads possibly?

Here is my code

import time
import threading

from PyQt5 import uic
from PyQt5.QtWidgets import (
    QApplication,
    QLabel,
    QLCDNumber,
    QMainWindow,
    QWidget,
)

class MyGUI(QMainWindow):

    def __init__(self):
        super(MyGUI, self).__init__()
        uic.loadUi("stopwatch.ui", self)
        self.show()
        self._start = 0.0
        self._elapsedtime = 0.0
        self._running = 0

        self.canvas_s1.setStyleSheet("background-color: yellow")

        self.start_s1.clicked.connect(self.start_timer)
        self.stop_s1.clicked.connect(self.stop_timer)
        self.reset_s1.clicked.connect(self.reset_timer)

            
    def start_timer(self):
        self._start = time.time() - self._elapsedtimed
        self._running = 1
        threading.Thread(target=self._update).start()
        self.canvas_s1.setStyleSheet("background-color: green")
        self._update()
        

    def stop_timer(self):
        self._running = 0
        self.canvas_s1.setStyleSheet("background-color: red")


    
    def reset_timer(self):
        self._start = time.time()
        self._elapsedtime = 0.0
        self.timer_s1.set("00:00:00")
        self._running = 0
        self.canvas_s1.setStyleSheet("background-color: yellow")
        

    def format_time_string(self, time_passed):
        return f"{int(hours):02d}:{int(mins):02d}:{int(secs):02d}"


    def _update(self):
        self._elapsedtime = time.time() - self._start
        self.timer_s1.setText(self.format_time_string(self._elapsedtime))
        if self._elapsedtime > 15:
            self.canvas_s1.setStyleSheet("background-color: orange")
        if self._running:
            self.after(100, self._update)


def main():
    app = QApplication([])
    window = MyGUI()
    app.exec_()


if __name__ == "__main__":
    main()

    
  • Qt does not support GUI operations of any kind outside the main thread. Please read a [basic tutorial on how to use threads with pyqt guis](https://realpython.com/python-pyqt-qthread/). – ekhumoro Apr 24 '23 at 10:31
  • The main reason for which your program crashes is that in `format_time_string` you're trying to use undefined variables (hours, mins, secs). But, even if you did, the concept is wrong. I suppose you're probably trying to follow a Youtube tutorial (Neural Nine), and unfortunately that tutorial is **completely** wrong about two things: 1. you must ***NEVER*** access UI elements directly from external threads (widgets are **not** thread safe); 2. using a thread with a while loop for a stop watch makes no sense at all, and doing it like that is **wrong**: just use QTimer and QElapsedTimer. – musicamante Apr 24 '23 at 17:23

0 Answers0