There is no way to pause Thread. However, You can imitate such a behavior by for example using Event from threading module. Personally I prefer toggling instead of using two buttons.
Here is simple code with Button implemented in PyQt6:
import sys
from threading import Thread, Event
from time import sleep
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton
class Worker(Thread):
def __init__(self, running_event: Event) -> None:
self.running_event = running_event
super().__init__()
def run(self) -> None:
"""
Worker is doing its job until running_event is set.
:return: None
"""
while self.running_event.wait():
print("Working on something...")
sleep(1) # Imitate code execution
if __name__ == "__main__":
app = QApplication(sys.argv)
# Create and set running Event
running_event = Event()
running_event.set()
widget = QWidget()
toggle_button = QPushButton("Pause", widget)
def toggle_running() -> None:
"""
Toggle state of running event.
:return: None
"""
if running_event.is_set():
running_event.clear()
toggle_button.setText("Resume")
else:
running_event.set()
toggle_button.setText("Pause")
# Connect toggle_button to our toggle function
toggle_button.clicked.connect(toggle_running)
# Create and start worker
worker = Worker(running_event)
worker.setDaemon(True)
worker.start()
# Show widget and start application
widget.show()
app.exec()