Python Forum
Can't stop keyboard listener to grab chars typed inside CTk window
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can't stop keyboard listener to grab chars typed inside CTk window
#1
Hey guys, what I am trying to do is simple, but I don't know what am I doing wrong:

1. I have keyboard class capturing the keystrokes typed in background; I still have variables capturing these keys for further actions.

2. In a moment of my code, I created a Custom Tkinter pop up window when the user can click in a option or select it by typing it's
correspondent number. I don't wanna any keys typed, while this CTk window is active, to be captured by my keyboard listener.

3. So, when I create my window i do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class CustomTkinterPopupSelector:
     
     
    def __init__(self, options,  key_listener):
         
         
     
        self.key_listener = key_listener  # Store the key_listener instance
        self.key_listener.popup_open = True  # Set the flag when popup is open
        print(f"Debug: Setting popup_open to True in CustomTkinterPopupSelector"# Debug log
         
 
        self.key_listener.active = False  # Deactivate the key listener
        
 
 
        self.root = ctk.CTk()  # Using customtkinter's CTk instead of tk.Tk
        ctk.set_appearance_mode("light")
        ctk.set_default_color_theme("blue")
 
 
        self.root.withdraw()  # Hide the main window
 
        self.top_window = ctk.CTkToplevel(self.root)  # Using customtkinter's CTkToplevel
        self.top_window.geometry("1200x500")
        self.top_window.title("Select Expansion")
 
        # Make the window modal
        self.top_window.grab_set()
 
 
 
         # To capture keypress events and paste the corresponding expansion
        self.top_window.bind('<Key>', lambda event: self.on_key(event, options))
 
        for i, option in enumerate(options):
            button = ctk.CTkButton(
                self.top_window,
                text=f"{i + 1}. {option}",
                command=lambda i=i: self.make_selection(i),
                fg_color="orange"# Set background to orange
                text_color="black",    # Set text to black
                font=ctk.CTkFont(family='Work Sans', size=16),
               
            )
            button.pack(padx=10, pady=10, anchor='w'# Left-align buttons
 
 
        # Attempt to bring Tkinter window to the foreground
        self.bring_window_to_foreground()
       
        self.root.mainloop()
 
 
 
######################################################################################
    def bring_window_to_foreground(self):
        self.top_window.update_idletasks()
        hwnd = win32gui.FindWindow(None, "Select Expansion")
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys("%")
        time.sleep(0.05)
        shell.SendKeys("%")
        win32gui.SetForegroundWindow(hwnd)
        # Send another Alt key to nullify the activation
        self.top_window.focus_force()
 
   
   
  ####################################################################################
    def make_selection(self, index):
        print(f"Debug: make_selection called. Popup open before: {self.key_listener.popup_open}")
 
        #Stop keyboard listener
        keyboard.unhook_all()
 
        # Wait for a small period to ensure the keyboard listener has fully stopped
        time.sleep(0.1)
         
         
        # Explicitly reset last_sequence and typed_keys to avoid capturing keys during popup
        self.key_listener.last_sequence = ""
        self.key_listener.typed_keys = ""
     
 
        #self.callback(index)
        self.top_window.grab_release()  # Release the grab (modal state)
        self.top_window.destroy()
        self.root.quit()
         # Add a small delay here
        time.sleep(0.1# You can adjust the duration
 
 
 
        # Explicitly call paste_expansion here to test
        selected_expansion_data = self.key_listener.expansions_list[index]
        self.key_listener.paste_expansion(
            selected_expansion_data["expansion"],
            format_value=selected_expansion_data["format_value"],
        )
 
        time.sleep(0.1# Add a slight delay
        #self.key_listener.popup_open = False  # Reset the flag when popup is closed
 
        print(f"Debug: make_selection called. Popup open after: {self.key_listener.popup_open}")
        
 
 
    def on_key(self, event, options):
        try:
             
            index = int(event.char) - 1  # Convert to integer and 0-based index
            if 0 <= index < len(options):
                self.make_selection(index)
                self.key_listener.popup_open = True  # Use self.key_listener to access the instance variable
                return
        except ValueError:
            pass  # Ignore non-integer keypress
The problem is that my main function to verify key presses is set to verify is the pop-up window is open or not. However is not working as after I typed the number, for instance "2", the option is pasted correctly but the number "2" is added to my variables and I dont wanna it., so I made this check:
1
2
3
4
def on_key_press(self, event):
        print(f"Debug: Checking popup_open in on_key_press: {self.popup_open}"# Debug log
        if self.programmatically_typing or self.popup_open == True# Skip if we are programmatically typing or popup is open
            return
I unhook the keyboard when the window is called, set the flag to open, and whatever I do, the any key I press inside the pop-up window is added to the variables after the code pastes the expansion. I need empty variables after that. When I just click the option everything works fine. Can someone give me a clue of whats going on here? What am I not stopping the keyboard to record the key presses inside the pop-up window?
Reply
#2
(Sep-23-2023, 03:16 PM)Valjean Wrote: Hey guys, what I am trying to do is simple, but I don't know what am I doing wrong:

1. I have keyboard class capturing the keystrokes typed in background; I still have variables capturing these keys for further actions.

2. In a moment of my code, I created a Custom Tkinter pop up window when the user can click in a option or select it by typing it's
correspondent number. I don't wanna any keys typed, while this CTk window is active, to be captured by my keyboard listener.

3. So, when I create my window i do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class CustomTkinterPopupSelector:
     
     
    def __init__(self, options,  key_listener):
         
         
     
        self.key_listener = key_listener  # Store the key_listener instance
        self.key_listener.popup_open = True  # Set the flag when popup is open
        print(f"Debug: Setting popup_open to True in CustomTkinterPopupSelector"# Debug log
         
 
        self.key_listener.active = False  # Deactivate the key listener
        
 
 
        self.root = ctk.CTk()  # Using customtkinter's CTk instead of tk.Tk
        ctk.set_appearance_mode("light")
        ctk.set_default_color_theme("blue")
 
 
        self.root.withdraw()  # Hide the main window
 
        self.top_window = ctk.CTkToplevel(self.root)  # Using customtkinter's CTkToplevel
        self.top_window.geometry("1200x500")
        self.top_window.title("Select Expansion")
 
        # Make the window modal
        self.top_window.grab_set()
 
 
 
         # To capture keypress events and paste the corresponding expansion
        self.top_window.bind('<Key>', lambda event: self.on_key(event, options))
 
        for i, option in enumerate(options):
            button = ctk.CTkButton(
                self.top_window,
                text=f"{i + 1}. {option}",
                command=lambda i=i: self.make_selection(i),
                fg_color="orange"# Set background to orange
                text_color="black",    # Set text to black
                font=ctk.CTkFont(family='Work Sans', size=16),
               
            )
            button.pack(padx=10, pady=10, anchor='w'# Left-align buttons
 
 
        # Attempt to bring Tkinter window to the foreground
        self.bring_window_to_foreground()
       
        self.root.mainloop()
 
 
 
######################################################################################
    def bring_window_to_foreground(self):
        self.top_window.update_idletasks()
        hwnd = win32gui.FindWindow(None, "Select Expansion")
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys("%")
        time.sleep(0.05)
        shell.SendKeys("%")
        win32gui.SetForegroundWindow(hwnd)
        # Send another Alt key to nullify the activation
        self.top_window.focus_force()
 
   
   
  ####################################################################################
    def make_selection(self, index):
        print(f"Debug: make_selection called. Popup open before: {self.key_listener.popup_open}")
 
        #Stop keyboard listener
        keyboard.unhook_all()
 
        # Wait for a small period to ensure the keyboard listener has fully stopped
        time.sleep(0.1)
         
         
        # Explicitly reset last_sequence and typed_keys to avoid capturing keys during popup
        self.key_listener.last_sequence = ""
        self.key_listener.typed_keys = ""
     
 
        #self.callback(index)
        self.top_window.grab_release()  # Release the grab (modal state)
        self.top_window.destroy()
        self.root.quit()
         # Add a small delay here
        time.sleep(0.1# You can adjust the duration
 
 
 
        # Explicitly call paste_expansion here to test
        selected_expansion_data = self.key_listener.expansions_list[index]
        self.key_listener.paste_expansion(
            selected_expansion_data["expansion"],
            format_value=selected_expansion_data["format_value"],
        )
 
        time.sleep(0.1# Add a slight delay
        #self.key_listener.popup_open = False  # Reset the flag when popup is closed
 
        print(f"Debug: make_selection called. Popup open after: {self.key_listener.popup_open}")
        
 
 
    def on_key(self, event, options):
        try:
             
            index = int(event.char) - 1  # Convert to integer and 0-based index
            if 0 <= index < len(options):
                self.make_selection(index)
                self.key_listener.popup_open = True  # Use self.key_listener to access the instance variable
                return
        except ValueError:
            pass  # Ignore non-integer keypress
The problem is that my main function to verify key presses is set to verify is the pop-up window is open or not. However is not working as after I typed the number, for instance "2", the option is pasted correctly but the number "2" is added to my variables and I dont wanna it., so I made this check:
1
2
3
4
def on_key_press(self, event):
        print(f"Debug: Checking popup_open in on_key_press: {self.popup_open}"# Debug log
        if self.programmatically_typing or self.popup_open == True# Skip if we are programmatically typing or popup is open
            return
I unhook the keyboard when the window is called, set the flag to open, and whatever I do, the any key I press inside the pop-up window is added to the variables after the code pastes the expansion. I need empty variables after that. When I just click the option everything works fine. Can someone give me a clue of whats going on here? What am I not stopping the keyboard to record the key presses inside the pop-up window?


Analyzing deeper the question, after hours spent, I guess is a question of nature of the keyboard library or tkinter, because no matter what flag I set, no matter when I hook or unhook the listener, the pop-up window stops the code execution, and everything I type when the pop-up window is active is somehow saved in a buffer and restored into the variables after the window is destroyed. Adding this information, I hope someone how knows more about the keyboard library and tkinter (or customTkinter) can light my way...
Reply
#3
Where is the key listener? How do you expect help understanding why the tkinter windows doesn't cooperate with the key listener when you don't show the key listener being made or the tkinter window being created.
Reply
#4
(Sep-24-2023, 04:35 AM)deanhystad Wrote: Where is the key listener? How do you expect help understanding why the tkinter windows doesn't cooperate with the key listener when you don't show the key listener being made or the tkinter window being created.

Sorry, I am new to programming. The custom tkinter window is called here, using the constructor of my previous message:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Multiple Expansions
        if len(expansions_list) > 1:
            self.expansions_list = expansions_list  # Store the expansions list
 
           [b] popup_selector = CustomTkinterPopupSelector(
                [exp["expansion"] for exp in expansions_list], self
            )[/b]
 
        # One expansion
        elif len(expansions_list) == 1# Handling single expansion
            print("Debug: Single expansion detected."# Debugging line
            expansion_data = expansions_list[0]
            self.paste_expansion(
                expansion_data["expansion"], format_value=expansion_data["format_value"]
            )
The key listener is the keyboard library. I just imported it. As I read, it creates its own thread. Then, in my listener.py I call on_key_press function, that i registered here in the constructor of my Keylistener class :
1
keyboard.on_press(lambda e: self.on_key_press(e))
to colelct the key presses:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
def on_key_press(self, event):
       print(
           f"Debug: Checking popup_open in on_key_press: {self.popup_open}"
       # Debug log
       if (
           self.programmatically_typing or self.popup_open == True
       ):  # Skip if we are programmatically typing or popup is open
           return
 
       print(
           "on_key_press called"
       # Debugging: Changed from on_key_release to on_key_press
       key = event.name
       print(
           f"Key pressed: {key}"
       # Debugging: Changed from Key released to Key pressed
 
       # Initialize variables to None at the start of the function
       expansion = None
       format_value = None
       self.requires_delimiter = None
       self.delimiters = None
 
       start_time = time.time()
 
       # Initialize self.last_sequence if not already done
       if not hasattr(self, "last_sequence"):
           self.last_sequence = ""
 
       if (
           self.ctrl_pressed
           or self.shift_pressed
           or self.alt_pressed
           or self.winkey_pressed
       ):
           return
 
       # CTRL
       if key == "ctrl":
           self.ctrl_pressed = False
 
       # Shift KEY
       elif key == "shift":
           self.shift_pressed = False
 
       # ALT
       elif key == "alt":
           self.alt_pressed = False
 
       # WINKEY
       elif key == "cmd":
           self.winkey_pressed = False
 
       # Ignore 'enter' when self.typed_keys is empty
       if key == "enter" or (key == "space" and not self.typed_keys):
           return
 
       if key not in self.omitted_keys:
           if self.shift_pressed:
               char = key.upper()  # Convert to upper case if Shift is pressed
               self.shift_pressed = False  # Reset the flag immediately after use
           else:
               char = key
 
           self.handle_accents(char)  # Handle accents
 
           print(f"Self Typed Keys:__ {self.typed_keys}")
           print(f"Last Sequence:__ {self.last_sequence}")
 
       else# Key is in omitted_keys
           if key == "backspace":
               self.typed_keys = self.typed_keys[:-1]
               self.last_sequence = self.last_sequence[:-1# Update last_sequence
 
           elif key == "space":
               self.typed_keys += " "
               self.last_sequence = ""  # Clear last_sequence
 
           elif key == "enter"# Handling the "Enter" key
               self.typed_keys += "\n"  # Add newline to last_typed_keys
               self.last_sequence = ""  # Clear last_sequence
 
      try:
           self.last_key = key
 
           if key not in self.omitted_keys:
               self.lookup_and_expand(self.last_sequence)
           else:
               if key == "space":
                   # Tokenize the sentence into words
                   words = word_tokenize(self.typed_keys)
 
                   # Get the last word
                   last_word = words[-1]
                   self.lookup_and_expand(last_word)
 
       except Exception as e:
           logging.error(f"Error in on_key_release: {e}")
 
       end_time = time.time()
       elapsed_time = end_time - start_time
       logging.info(f"on_key_release processing took {elapsed_time:.2f} seconds")
Let me know if it helps. Thanks
Reply
#5
Please post the code for the keypad listener. My guess is the tkinter mainloop() blocks the listener, but I have no way of knowing that from the code you have posted.

I really don't care about the tkinter window. tkinter or custom tkinter all work the same. Create the root. Populate with widgets. Call mainloop(). Block program until root window is deleted. I do find it odd that you hide the root window. Why are you creating a toplevel window instead of using root?
Valjean likes this post
Reply
#6
(Sep-24-2023, 01:03 PM)deanhystad Wrote: Please post the code for the keypad listener. My guess is the tkinter mainloop() blocks the listener, but I have no way of knowing that from the code you have posted.

I really don't care about the tkinter window. tkinter or custom tkinter all work the same. Create the root. Populate with widgets. Call mainloop(). Block program until root window is deleted. I do find it odd that you hide the root window. Why are you creating a toplevel window instead of using root?

Quote:First, I am using chatGPT for helping me starting the code: here what I got after raising your questions:


Your code is built on top of CustomTkinter, a custom tkinter wrapper. You're using the ctk.CTk() for the root window and ctk.CTkToplevel() for the top-level window. You also make use of the bring_window_to_foreground function to attempt to bring the tkinter window to the foreground.

The keypresses might be getting recorded while tkinter is active due to how the tkinter main event loop (mainloop()) and the keyboard listener are interacting. If the tkinter main loop is blocking the event loop of your keyboard listener, then they won't work well together.

Here are some points to consider:

Why Use Top-level Window?: You asked why a top-level window is used instead of the root window. Using a top-level window allows for the root window to remain hidden, making it easier to show/hide the popup without affecting other parts of the GUI. It's a common practice when building tkinter applications.

Keypad Listener: You mentioned you found an answer online suggesting the mainloop() might be blocking the keyboard listener. Yes, that could be the issue. It's hard to say without seeing how you've implemented the keyboard listener. You might want to look into running the keyboard listener in a separate thread.

I dont have a separate keypad function. All my keypresses are recorded in on_key_press function.


I am almost sure that tkinter mainloop is blocking the keyboard listener. As I said, keyboard library already creates its own thread. So maybe keyboard and tkinter are in the same thread, I dont understand it yet very well. In the end, I just wanna a simple popup (focused ---that's hard to do when your main app is not on focus (I am typing my texts in Notepad)) that when active, stops my keyboard listener, and after destroyed resumes it. It maybe tkinter or any other library. The way is is now, everything I type while the tkinter pop up is active is being captured ny the keyboard listener and then restored back to the variables after the tkinter window is closed.
Reply
#7
Quote:I dont have a separate keypad function. All my keypresses are recorded in on_key_press function.
There must be some code that you are running to make python listen for key presses. What package are you using to listen? It probably has it's own version of mainloop() that runs until your ok_key_press function does something to stop it.
Reply
#8
Quote: I don't wan(t) any keys typed, while this CTk window is active, to be captured by my keyboard listener.
Use an Entry instead of a keylogger and set the state to disabled when you don't want to capture input.
Reply
#9
I changed some code and hope what I write here is helpful:

I have a main window in pywebview and I start it this way (resumed code):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
    # ----------------------------------------------------------------CREATE WINDOW
 
    def create_and_position_window(self):
        monitor = get_monitors()[0]
        screen_width = monitor.width
        screen_height = monitor.height
        pos_x = (screen_width - WINDOW_WIDTH) // 2
        pos_y = (screen_height - WINDOW_HEIGHT) // 2
 
        self.window = webview.create_window(
            title=WINDOW_TITLE,
            url="index.html",
            frameless=False,
            resizable=True,
            js_api=self,
            min_size=(screen_width // 2, WINDOW_HEIGHT),
        )
 
        time.sleep(1)
 
        window = get_window()
 
        if window:
            window.moveTo(pos_x, pos_y)
 
        threading.Thread(target=self.call_load_handler_after_delay).start()
 
    def call_load_handler_after_delay(self):
        time.sleep(0.5)
        load_handler(self.window)
 
 
# Define a function to handle triggering the popup
def handle_popup_trigger(api_instance):
    while True:
        api_instance.trigger_popup_event.wait()
         
        # Fetch the options from api_instance.listener_instance.expansions_list
        options = api_instance.listener_instance.expansions_list
         
        # Show the Tkinter popup here by instantiating CustomTkinterPopupSelector
        popup = CustomTkinterPopupSelector(options, api_instance.listener_instance)
         
        api_instance.trigger_popup_event.clear()
 
 
 
def get_window():
    windows = gw.getWindowsWithTitle(WINDOW_TITLE)
    return windows[0] if windows else None
 
 
def load_handler(window):
    pass
 
 
 
 
 
def start_app(api_instance):
    api_instance.create_and_position_window()
    webview.start(http_server=True)
     
    trigger_event = threading.Event()  # Create an Event object
    key_listener = KeyListener(api_instance, trigger_event)  # Pass the Event object
    key_listener.start_listener()  # Assuming you have a start_listener method in KeyListener
 
 
 
 
def start_webview(api_instance):
    try:
        start_app(api_instance)  # Pass the api_instance here
    except Exception as e:
        print(f"An error occurred: {e}")
 
 
 
 
 
# Moved this block into a main block to control execution flow
if __name__ == "__main__":
    # Initialize the Api class
    api = Api()
 
 
# Start the function in a separate thread
    popup_thread = Thread(target=handle_popup_trigger, args=(api,))  # <-- Add this line
    popup_thread.start()  # <-- Add this line
 
 
    # Initialize and start the webview in the main thread
    start_webview(api)
I started my keyboard listener (keyboard library) in main thread. Then I have this file code for the keyboard listener:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
########################################################################
class KeyListener:
 
 
 
    def __init__(self, api, trigger_event):  # <-- Add a trigger_event parameter
         
         
 
        self.popup_closed_event = threading.Event()  # Add this line
 
        self.trigger_event = trigger_event  # <-- Store the Event object
         
       
 
        self.trigger_event.clear()
        self.popup_closed_event.clear()
 
 
 
 
        self.popup_open = False  # Initialize the flag here as False
        print(f"Debug: Initializing popup_open to False in KeyListener"# Debug log
 
        self.expansions_list = []  # Define the expansions_list
        
 
        keyboard.on_press(lambda e: self.on_key_press(e))
        keyboard.on_release(lambda e: self.on_key_release(e))
 
        self.programmatically_typing = False  # Initialize the flag here
 
        self.last_word = ""  # Initialize last_word
        self.word_buffer = deque([], maxlen=50# Initialize with an empty deque
 
        self.ctrl_pressed = False
        self.shift_pressed = False
        self.alt_pressed = False
        self.winkey_pressed = False
 
        self.api = api
 
        self.key_to_str_map = {
            "Key.space": "space",
            "Key.enter": "enter",
            # Add more if needed
        }
 
        self.requires_delimiter = None
        self.delimiters = None
 
        self.accent = False
        self.last_key = None
        self.typed_keys = ""
 
   
        self.resetting_keys = set(["space"])
 
 
 
 
 
    def stop_listener(self):
        print ("Stopping listener...")
        
        keyboard.unhook_all()
        self.trigger_event.clear()
 
 
    def start_listener(self):
        print ("Starting listener...")
        keyboard.on_press(lambda e: self.on_key_press(e))
        keyboard.on_release(lambda e: self.on_key_release(e))
        self.trigger_event.set()
 
     
 
 
    def paste_expansion(self, expansion, format_value):
        print(
            f"Debug: paste_expansion called with expansion: {expansion}, format_value: {format_value}"
        )
        self.programmatically_typing = True  # Set the flag
        
 
      
        keyboard.press("ctrl")
        keyboard.press("shift")
        keyboard.press_and_release("left arrow")
        keyboard.release("shift")
        keyboard.release("ctrl")
        keyboard.press_and_release("backspace")
 
        if expansion is not None:
            format_value = int(format_value)
 
            if format_value == 0:
                pyperclip.copy(expansion)
                print("Debug: Using REGULAR clipboard.")
            else:
                dirty_HTML = expansion  # Your variable
                html_clipboard.PutHtml(dirty_HTML)  # Your logic
                print("Debug: Using HTML clipboard.")
 
            # Now paste
            keyboard.press_and_release("ctrl+v")
 
 
        self.programmatically_typing = False  # Reset the flag
 
        # Remove the last incorrect word from self.typed_keys
        self.typed_keys = self.typed_keys.rstrip(self.last_word)
 
        # Add the corrected word
        self.typed_keys += expansion + " "
 
        self.last_word = expansion  # Update the last word to the new expanded word
        self.word_buffer.append(expansion)  # Add the expanded word to the buffer
 
   
    # -------------------------------------------------------------------------
 
    def lookup_and_expand(self, sequence):
        hardcoded_suffixes = {
            "çao": ("ção", r"(?<![ã])\bçao\b"),
            "mn": ("mento", r".mn"),
            "ao": ("ão", r".ao"),
        }
 
        words = word_tokenize(sequence)
        if words:
            last_word = words[-1]
 
        for i in range(len(last_word) - 1, -1, -1):
            suffix = last_word[i:]
            if suffix in hardcoded_suffixes:
                expansion, regex_pattern = hardcoded_suffixes[suffix]
                if re.search(regex_pattern, last_word):
                    prefix = last_word[:i]
                    expansion = prefix + expansion
 
                    if self.typed_keys.endswith(last_word + " "):
                        self.typed_keys = self.typed_keys[: -len(last_word) - 1]
                    elif self.typed_keys.endswith(last_word):
                        self.typed_keys = self.typed_keys[: -len(last_word)]
 
                    if self.word_buffer and self.word_buffer[-1] == last_word:
                        self.word_buffer.pop()
 
                    self.paste_expansion(expansion, format_value=0)
                    return
 
        expansions_list = []
        try:
            expansions_list = lookup_word_in_all_databases(sequence)
        except ValueError:
            print("Not enough values returned from lookup
################################################################################################ Multiple Expansions
        if len(expansions_list) > 1:
             
            if len(expansions_list) > 1:
                
                self.expansions_list = expansions_list  # Store the expansions list
 
                self.stop_listener()  # Stop the listener here
 
                self.popup_closed_event.clear()  # Clear the event
                self.trigger_event.set()  # Signal the main thread to show the popup
 
                # Wait for popup to close
                self.popup_closed_event.wait()  # Assuming you have a threading.Event() for this
 
                self.start_listener()  # Start the listener again
 
 
        
        ################################################################################################### One expansion
        elif len(expansions_list) == 1# Handling single expansion
            print("Debug: Single expansion detected."# Debugging line
            expansion_data = expansions_list[0]
            self.paste_expansion(
                expansion_data["expansion"], format_value=expansion_data["format_value"]
            )
 
        ######
        try:
            (
                expansion,
                format_value,
                self.requires_delimiter,
                self.delimiters,
            ) = lookup_word_in_all_databases(sequence)
 
        except ValueError:
            print("Not enough values returned from lookup")
            expansion = format_value = self.requires_delimiter = self.delimiters = None
 
        #####
        if self.requires_delimiter == "yes":
            delimiter_list = [item.strip() for item in self.delimiters.split(",")]
            key_str = self.key_to_str_map.get(str(self.last_key), str(self.last_key))
            if key_str in delimiter_list:
                if expansion is not None:
                    self.paste_expansion(expansion, format_value=format_value)
                    self.typed_keys = ""
 
        elif self.requires_delimiter == "no":
            if expansion is not None:
                self.paste_expansion(expansion, format_value=format_value)
                self.typed_keys = ""
 
     
    ################################################################
 
    def on_key_press(self, event):
         
         
         
        print(
            f"Debug: Checking popup_open in on_key_press: {self.popup_open}"
        # Debug log
        if (
            self.programmatically_typing or self.popup_open == True
        ):  # Skip if we are programmatically typing or popup is open
            return
 
        print(
            "on_key_press called"
        # Debugging: Changed from on_key_release to on_key_press
        key = event.name
        print(
            f"Key pressed: {key}"
        # Debugging: Changed from Key released to Key pressed
 
        # Initialize variables to None at the start of the function
        expansion = None
        format_value = None
        self.requires_delimiter = None
        self.delimiters = None
 
        start_time = time.time()
 
        # Initialize self.last_sequence if not already done
        if not hasattr(self, "last_sequence"):
            self.last_sequence = ""
 
        if (
            self.ctrl_pressed
            or self.shift_pressed
            or self.alt_pressed
            or self.winkey_pressed
        ):
            return
 
        # CTRL
        if key == "ctrl":
            self.ctrl_pressed = False
 
        # Shift KEY
        elif key == "shift":
            self.shift_pressed = False
 
        # ALT
        elif key == "alt":
            self.alt_pressed = False
 
        # WINKEY
        elif key == "cmd":
            self.winkey_pressed = False
 
        # Ignore 'enter' when self.typed_keys is empty
        if key == "enter" or (key == "space" and not self.typed_keys):
            return
 
        if key not in self.omitted_keys:
            if self.shift_pressed:
                char = key.upper()  # Convert to upper case if Shift is pressed
                self.shift_pressed = False  # Reset the flag immediately after use
            else:
                char = key
 
            self.handle_accents(char)  # Handle accents
 
            print(f"Self Typed Keys:__ {self.typed_keys}")
            print(f"Last Sequence:__ {self.last_sequence}")
 
        else# Key is in omitted_keys
            if key == "backspace":
                self.typed_keys = self.typed_keys[:-1]
                self.last_sequence = self.last_sequence[:-1# Update last_sequence
 
            elif key == "space":
                self.typed_keys += " "
                self.last_sequence = ""  # Clear last_sequence
 
            elif key == "enter"# Handling the "Enter" key
                self.typed_keys += "\n"  # Add newline to last_typed_keys
                self.last_sequence = ""  # Clear last_sequence
 
                # ---------------------------------------WORDS--------------------------------
                # Tokenize the sentence into words
                words = word_tokenize(self.typed_keys)
                # Get the last word
                last_word = words[-1]
 
                self.fix_double_caps(last_word)  # Call fix_double_caps here
                self.lookup_and_expand(last_word)
 
                # --------------------------------------SENTENCES-----------------------------
                # Sentence Tokenization
                sentences = sent_tokenize(self.typed_keys)
                last_sentence = sentences[-1] if sentences else ""
 
                # ---------------------------------------ENTITIES--------------------------------
                # Tokenization
                tokens = word_tokenize(
                    self.typed_keys
                # Make sure self.typed_keys is a string
                tags = pos_tag(tokens)
                entities = ne_chunk(tags)
 
                # ---------------------------------------COLLECT DATA
                # Call the new method here
                self.capture_ngrams_and_collocations()
 
                # --------------------------------PRINTS--------------------------------
                print(f"Entities = {entities}")
 
                print(f"Sentence List= {sentences}")
                print(f"Last Sentence = {last_sentence}")
 
                print(f"Words List= {words}")
                print(f"Last Word= {last_word}")
 
        try:
            self.last_key = key
 
            if key not in self.omitted_keys:
                self.lookup_and_expand(self.last_sequence)
            else:
                if key == "space":
                    # Tokenize the sentence into words
                    words = word_tokenize(self.typed_keys)
 
                    # Get the last word
                    last_word = words[-1]
                    self.lookup_and_expand(last_word)
 
        except Exception as e:
            logging.error(f"Error in on_key_release: {e}")
 
        end_time = time.time()
        elapsed_time = end_time - start_time
        logging.info(f"on_key_release processing took {elapsed_time:.2f} seconds")
and this code for the popup window (tkinter)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
class CustomTkinterPopupSelector:
     
     
    def __init__(self, options,  key_listener):
         
         
        
        self.key_listener = key_listener  # Store the key_listener instance
         
        self.key_listener.popup_open = True  # Set the flag when popup is open
        print(f"Debug: Setting popup_open to True in CustomTkinterPopupSelector"# Debug log
         
 
 
        self.root = ctk.CTk()  # Using customtkinter's CTk instead of tk.Tk
        ctk.set_appearance_mode("light")
        ctk.set_default_color_theme("blue")
 
 
        self.root.withdraw()  # Hide the main window
 
        self.top_window = ctk.CTkToplevel(self.root)  # Using customtkinter's CTkToplevel
        self.top_window.geometry("1200x500")
        self.top_window.title("Select Expansion")
 
        # Make the window modal
        self.top_window.grab_set()
 
 
 
         # To capture keypress events and paste the corresponding expansion
        self.top_window.bind('<Key>', lambda event: self.on_key(event, options))
 
        for i, option in enumerate(options):
            button = ctk.CTkButton(
                self.top_window,
                text=f"{i + 1}. {option}",
                command=lambda i=i: self.make_selection(i),
                fg_color="orange"# Set background to orange
                text_color="black",    # Set text to black
                font=ctk.CTkFont(family='Work Sans', size=16),
               
            )
            button.pack(padx=10, pady=10, anchor='w'# Left-align buttons
 
 
        # Attempt to bring Tkinter window to the foreground
        self.bring_window_to_foreground()
       
        self.root.mainloop()
 
 
 
######################################################################################
     
    def bring_window_to_foreground(self):
        self.top_window.update_idletasks()
        hwnd = win32gui.FindWindow(None, "Select Expansion")
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys("%")
        time.sleep(0.05)
        shell.SendKeys("%")
        win32gui.SetForegroundWindow(hwnd)
        # Send another Alt key to nullify the activation
        self.top_window.focus_force()
 
   
   
  ####################################################################################
    def make_selection(self, index):
         
         
        print(f"Debug: make_selection called. Popup open before: {self.key_listener.popup_open}")
 
        # Explicitly reset last_sequence and typed_keys to avoid capturing keys during popup
        self.key_listener.last_sequence = ""
        self.key_listener.typed_keys = ""
 
        #self.callback(index)
        self.top_window.grab_release()  # Release the grab (modal state)
        self.top_window.destroy()
        self.root.quit()
         # Add a small delay here
        time.sleep(0.1# You can adjust the duration
 
 
 
        # Explicitly call paste_expansion here to test
        selected_expansion_data = self.key_listener.expansions_list[index]
        self.key_listener.paste_expansion(
            selected_expansion_data["expansion"],
            format_value=selected_expansion_data["format_value"],
        )
 
        time.sleep(0.1# Add a slight delay
        #self.key_listener.popup_open = False  # Reset the flag when popup is closed
        self.key_listener.popup_open = False  # Reset the flag when popup is closed
 
        print(f"Debug: make_selection called. Popup open after: {self.key_listener.popup_open}")
        
        
 
 
    def on_key(self, event, options):
        try:
             
            index = int(event.char) - 1  # Convert to integer and 0-based index
            if 0 <= index < len(options):
                self.make_selection(index)
                self.key_listener.popup_open = True  # Use self.key_listener to access the instance variable
                return
        except ValueError:
            pass  # Ignore non-integer keypress
Resuming.. the popup is called, but as soon as I choose an option, the keyboard stops but wont restart, unless I close the app, I see then the message starting listener showing...

this is my print:



Last Sequence:__ ce3
Debug: Initializing popup_open to False in KeyListener
Stopping listener...
Debug: Setting popup_open to True in CustomTkinterPopupSelector
Debug: make_selection called. Popup open before: True
Debug: paste_expansion called with expansion: Art. 3º Qualquer cidadão pode pretender investidura em cargo eletivo, respeitadas as condições constitucionais e legais de elegibilidade e incompatibilidade., format_value: 0
Debug: Using REGULAR clipboard.
Debug: make_selection called. Popup open after: False


I dont know is something with the unhooking and rehooking, threads... I dont know :(
Reply
#10
Was there something in your log file that you did not expect?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  scan network and grab details of hosts found robertkwild 5 1,393 Aug-07-2024, 05:21 PM
Last Post: Larz60+
Question [PyMuPDF] Grab all strings of a given size? Winfried 3 1,639 Dec-26-2023, 07:39 AM
Last Post: Pedroski55
  Is there a way to call and focus any popup window outside of the main window app? Valjean 6 5,732 Oct-02-2023, 04:11 PM
Last Post: deanhystad
  Pyspark Window: perform sum over a window with specific conditions Shena76 0 2,023 Jun-13-2022, 08:59 AM
Last Post: Shena76
  [SOLVED] [ElementTree] Grab text in attributes? Winfried 3 2,585 May-27-2022, 04:59 PM
Last Post: Winfried
  Screen capture opencv - grab error Kalman15 1 2,855 Jan-27-2022, 12:22 PM
Last Post: buran
  cut string after tow known chars? korenron 3 2,405 Oct-28-2021, 01:23 PM
Last Post: korenron
  keyboard listener DPaul 5 4,783 Mar-28-2021, 09:15 PM
Last Post: Larz60+
  eliminating letters when typed in python window deebo 0 2,308 Jan-05-2021, 09:26 AM
Last Post: deebo
  Keyboard Module Python - Suppress input while writing to window ppel123 0 3,711 Apr-08-2020, 02:51 PM
Last Post: ppel123

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020