'Move function to thread to avoid interface block & program closed error

Please don't close this question like it was answered here mouse release event on entire screen Because it's not answered in there, my problem here is interface block threading problem

When clicking on a button, my code locks the entire interface.

This is my code:

from pynput.keyboard import Key, Listener
from pynput.keyboard import Key, Controller
from pynput import keyboard as kb
import time
import sys
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication, QDialog
from PySide6.QtCore import QFile

class EasyKey:
    def __init__(self):
        super(EasyKey, self).__init__()
        self.ui = QUiLoader().load(QFile("Edit.ui"))
        self.ui.Apply.clicked.connect(self.iniciar)  # llamada a al funcion iniciar

    def iniciar(self):
        teclashu = Controller()
        tecla = Controller()
        selecion = (
            self.ui.HotkeyNum.text()
        )  # varibles guardadas por datos introducidos por el usuario
        selecion_2 = selecion.swapcase()
        edic = self.ui.editionNum.text()
        selec = self.ui.EditionSelecNum.text()
        delay = int(self.ui.DelayNum.text())
        delay = delay / 1000

        def edit(key):  # funcion que recibe un parametro de teclado ingresado
            if (key == kb.KeyCode.from_char(selecion)) or (
                key == kb.KeyCode.from_char(selecion_2)
            ):  # Si "key" ingresado por el usario es igual a la variable asignada por el usuario
                tecla.press(edic)
                time.sleep(delay)
                teclashu.press(selec)
                time.sleep(delay)
            if key == Key.delete:
                return False

        def soltar(key):
            if key == kb.KeyCode.from_char(selec):
                tecla.release(edic)
                time.sleep(delay)
                teclashu.release(selec)
                time.sleep(delay)

        with Listener(
            on_press=edit, on_release=soltar
        ) as listener:  # ojente por teclado que llama a las funciones cada ves que se cumple la condicion del "key"
            listener.join()



if __name__ == "__main__":
    app = QApplication(sys.argv)
    myapp = EasyKey()
    myapp.ui.show()
    sys.exit(app.exec())

This would be the program:

enter image description here

I enter values in the left columns, and click on Apply, then it hangs.

I don't know much about Python, but in C# this can be solved with a thread or a background worker. The thing is that in Python I don't know how to do that.

It will even crash:

enter image description here

How can I do so that it doesn't crash when I click?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source