I have a function in a tkinter application that does some operations on the content of the clipboard, pastes the result to a Text widget, and then should return to the previous application. For the last part I'm generating an Alt-Tab using pynput.
def invert_clipboard(e=None):
txt = root.clipboard_get()
if not txt:
return
tokens = re.split('\s+', txt.strip())
if len(tokens) >= 2:
out = tokens[len(tokens)-1].strip() + ', '
for i in range(len(tokens)-1):
out += tokens[i]
if i < len(tokens) - 2:
out += ' '
else:
out = txt.strip()
out += '#'
input_text.insert(tk.INSERT, out)
global dirty
dirty = True
thread = Thread(target=switch_window)
thread.start()
def switch_window():
root.update_idletasks()
with keyboard.pressed(Key.alt):
keyboard.press(Key.tab)
keyboard.release(Key.tab)
keyboard.release(Key.alt)
The function can be accessed via a menu item:
macros_menu.add_command(
label='Invert',
command=invert_clipboard,
accelerator="Ctrl+M"
or via a keyboard shortcut:
root.bind('<Control-m>', lambda event:invert_clipboard(None))
When called from the menu, everything works as intended; when called from the keyboard shortcut, the return to previous doesn't quite work. I see the group of thumbnails of the open apps, with the expected app highlighted, but pressing Enter is required to maximize it.
I assume I'm not handling the keyboard event correctly in the bind, but I have only a murky understanding of how to do so. Any suggestions? Thanks.