How to clear keyboard.read_event()?

Viewed 34

code:

from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *

import keyboard
import time
import threading
import os
import sys
import queue

app = QApplication([])

class MainWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.thread1 = Thread1()

        self.start_button = QPushButton("start",self)
        self.stop_button = QPushButton("stop",self)
        self.stop_button.move(250,0)

        self.stop_button.clicked.connect(self.StopMethod)
        self.start_button.clicked.connect(self.StartMethod)
    def StopMethod(self):
        self.thread1.thread_state = False
        keyboard.unhook_all() #erase this and press any key,thread will be finished without error
        print(self.thread1.is_alive())
    def StartMethod(self):
        self.thread1.thread_state = True
        self.thread1.start()
    def closeEvent(self, event):
        self.thread1.thread_state = False
        keyboard.unhook_all()
        print(self.thread1.is_alive())


class Thread1(threading.Thread):
    def __init__(self):
        super().__init__()
        self.thread_state = True
    def run(self):
        while self.thread_state:
            key = keyboard.read_event()

            if key.event_type == keyboard.KEY_DOWN:
                print(key.name)

main_widget = MainWidget()
main_widget.show()
app.exec()

code description:

when "start" button clicked, thread is started, and "stop" button makes to esacpe from while loop

problem:

whenever "stop" button clicked, thread must be finished without error, but thread is keep alive. On the other hand,With using keyboard.hook() like this:

class Thread1(threading.Thread):
    def __init__(self):
        super().__init__()
        self.thread_state = True
    def run(self):
        key_hook = keyboard.hook(self.Method1)
        while self.thread_state:
           pass
    def Method1(self,event):
        if event.event_type == keyboard.KEY_DOWN:
            print(event.name)

This works well without error, but whenever you press multiple keys, the key stroke slowly reacts, and i dont want it. In my think, the keyboard.read_event() is keep holding some key input. Is there a way to solve this problem?

0 Answers
Related