按下任意键时,从剪贴板键入下一个字符,同时抑制键盘输入

问题描述 投票:0回答:1

我正在尝试创建一个程序,当激活选定的键绑定时,将抑制您的键盘输入,但将使用一个模块从剪贴板键入下一个字符。结果应该允许这样:

  1. 设置任意选择的按键绑定,然后启动应用程序
  2. 自由打字,做任何事
  3. 激活按键绑定,您的按键将与输出不匹配,例如;如果你按“j”,它实际上会按“T”,因为“T”是剪贴板中的第一项; “猫”,然后当您按任意键(例如“7”)时,它会键入“h”,因为它是剪贴板中的下一个字符。
  4. 可以随时按“ESC”取消抑制和模拟打字,否则当剪贴板打字完成后程序将自动关闭。

这是我的代码:

import tkinter as tk
from pynput import keyboard
import threading
import pyperclip  # For accessing the clipboard
import pyautogui

# Global variables
block_keys = False
selected_key = None
keyboard_listener = None
clipboard_content = pyperclip.paste()  # Get the clipboard content
listClipboard = [char for char in clipboard_content]
print(listClipboard)

# Function to listen for the keybind and start blocking
def listen_for_keybind():
    def on_press_keybind(key):
        global block_keys
        if key == selected_key:
            print(f"Keybind {selected_key} activated")
            global char_index
            char_index = 0  # Reset character index
            block_keys = True  # Start blocking keys
            start_blocking_listener()  # Start blocking key presses when keybind is activated
            return False  # Stop the keybind listener once the keybind is pressed

    with keyboard.Listener(on_press=on_press_keybind) as keybind_listener:
        keybind_listener.join()


controller = keyboard.Controller()
# Function to start the listener for blocking all key presses 
def start_blocking_listener():
    global keyboard_listener, listener

    # Function to handle key presses 
    # 
    def on_press(key):
        global listClipboard, keyboard_listener, listener
        print(f"Key pressed, not registered: {key}")
        
        if str(key) == "Key.esc":
            stop_blocking()
            return


        if listClipboard:
            keyboard_listener.stop()
            keyboard_listener = None
            pyautogui.typewrite(listClipboard[0])
            print(f"Typed: {listClipboard[0]}")
            listClipboard.pop(0)
            keyboard_listener = keyboard.Listener(on_press=on_press, suppress=True)
            keyboard_listener.start()



        

    # Disable keyboard events and print a message on key press
    keyboard_listener = keyboard.Listener(on_press=on_press, suppress=True)
    keyboard_listener.start()

def stop_blocking():
    global keyboard_listener
    global block_keys
    block_keys = False
    if keyboard_listener is not None:
        keyboard_listener.stop()
    print("Blocking disabled, typing enabled")

# Function to set the keybind
def set_keybind():
    add_button.config(text="Press any key...", state="disabled")

    
    def on_key_press(key):
        global selected_key
        selected_key = key
        add_button.config(text=f"Keybind set to: {key}", state="normal")
        listener.stop()

    global listener
    listener = keyboard.Listener(on_press=on_key_press)
    listener.start()

# Function to activate the keybind listener
def activate_keybind():
    if selected_key:
        root.withdraw()  # Minimize the window
        # Start a separate thread to listen for the keybind activation
        thread = threading.Thread(target=listen_for_keybind)
        thread.daemon = True
        thread.start()
    else:
        tk.messagebox.showerror("Error", "Please set a keybind first.")

# Function to quit the application
def quit_app():
    stop_blocking()
    root.quit()

# Set up the GUI
root = tk.Tk()
root.title("Keybind Blocking App")

label = tk.Label(root, text="Click the button below to set the keybind:")
label.pack(pady=10)

add_button = tk.Button(root, text="Add Keybind", command=set_keybind)
add_button.pack(pady=5)

set_button = tk.Button(root, text="Start Blocking", command=activate_keybind)
set_button.pack(pady=5)

quit_button = tk.Button(root, text="Quit", command=quit_app)
quit_button.pack(pady=5)

root.mainloop()

我尝试在controller.type()之前取消抑制,但随后重新启用它,这确实解决了它将controller.type()注册为下一个键盘输入的问题,但它仍然不会输入剪贴板中的下一个字符。

诗。有一些小错误,例如在未设置按键绑定的情况下启动应用程序,也许您应该首先将“0”作为激活应用程序的按键,因为这就是我测试过的全部内容。

如有帮助,我们将不胜感激。

python tkinter input keyboard clipboard
1个回答
0
投票

您需要做的就是让绑定函数返回字符串

"break"
以防止默认行为。然后您可以插入任何您想要的内容。

在以下示例中,将某些内容复制到剪贴板,然后运行代码,并在单击文本小部件后按几次逗号。

import tkinter as tk

clipboard = None
def replace_keystroke(event):
    global clipboard
    if clipboard is None:
        clipboard = root.clipboard_get()
    event.widget.insert("insert", clipboard[0])
    clipboard = clipboard[1:]
    return "break"

root = tk.Tk()
text = tk.Text(root, wrap="word")
text.pack(fill="both", expand=True)
text.bind("<comma>", replace_keystroke)

tk.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.