Python 3, Keyboard module -How to stop the default action when adding a hotkey (workaround found)

Viewed 27

I'm trying to overwrite an existing keyboard function on the enter key with a custom hotkey. The problem is, I cannot stop the default action from occurring also. Worse yet, it occurs after the custom action, so I don't have the chance to retroactively correct it as well.

Here are the relevant parts of the code:

from tkinter import *
from tkinter import ttk
from keyboard import *

root = Tk()
root.geometry('400x300')

'''This is the problematic function called by the hotkey'''
def entr_key(text): 
    '''Enter key results in printing of the line to the right of cursor'''
    curs_pos = text.index(INSERT)
    right_hand = text.get(curs_pos,END)
    right_hand = right_hand.split('\n')[:1]  #lines -> strs in a list, selects the first
    print (right_hand)
    return


'''THIS IS THE MAIN WIDGET FOR THIS FRAME'''
text_view = ttk.Frame(root, padding=10)
text_view.grid() 
text_box = Text(text_view, width=45, wrap=WORD)
text_box.grid(column=0, row=1)
text_box.insert('1.0', 'This is a Text widget demo,\nThis text is aimed at testing the enter key function')

add_hotkey("enter", lambda: entr_key(text_box))

root.mainloop()

(I've changed up some variable names to be more understandable, apologies if I missed any but it's not the source of the problem!)

I've also (unsuccesfully) tried other ways of doing this, eg:

while True:
     if is_pressed('enter'):
         entr_key(text_box)    

'''AND ALSO'''
    
on_press_key("enter", lambda x=None: entr_key(text_box))

Just to be clear, I don't want the default action of enter key moving the text to a new line.

I need either a way to "break" the key event so that only the custom action takes place, or a way for the custom action to occur after default action, so I can retroactively edit it out

EDIT!!! I've found a workaround: at the start of entr_key() I call time.sleep(0.01). During this, the default action of the enter key occurs first, and I can retroactively edit it out when the custom function resumes. The delay is slight enough to not be noticeable at all. But still, if anyone knows how to prevent the default action from occurring completely, I would really appreciate it.

0 Answers
Related