首页 > 解决方案 > 在python中为docx实现键盘

问题描述

我正在 python 中为我想在 word 文档中使用的特殊字符实现一个键盘。我正在寻找一种将整个字符串(没有击键序列)发送到文档的方法。我尝试使用 pyautogui 但我找不到任何功能(因为键盘语言可能会影响击键效果,我不想使用击键)

有没有办法做到这一点?例如,我想将一个函数绑定到一个按钮,按下该按钮时会写上“hello world!”。到word文档。

谢谢!

标签: pythonuser-interfacekeyboarddocx

解决方案


我不知道这对你有多大帮助。但是试试这个。更改此代码并在函数 key_input 中插入您想要的值,当值是您需要的时候。

from tkinter import *
import tkinter
from functools import partial

root = Tk()
root.title("Keyboard on screen")
root.resizable(0, 0)


def key_input(value):
    if value == "<-":
        insert_text = entry.get("1.0", "end-2c")
        entry.delete("1.0", "end")
        entry.insert("1.0", insert_text, tkinter.END)
    elif value == " Space ":
        entry.insert(tkinter.END, ' ')
    elif value == "Tab":
        entry.insert(tkinter.END, '    ')
    else:
        entry.insert(tkinter.END, value)


entry = Text(root, width=138, font=('Helvetica', 11, 'bold'))
entry.grid(row=1, columnspan=40)

keys = ['!', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '<-', '7', '8', '9', '-',
        'Tab', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', '[', ']', '4', '5', '6', '+',
        '<', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '_', '>', '1', '2', '3', '/',
        ' Space ']

rows = 2
columns = 0

for key in keys:
    key_command = lambda x = key: key_input(x)
    if key != ' Space ':
        tkinter.Button(root, text=key, width=5, padx=3, pady=3, bd=5, font=('Helvetica', 12, 'bold'),
                       activebackground="#ffffff", activeforeground="#000000", relief='raised',
                       command=key_command).grid(row=rows, column=columns)
    if key == ' Space ':
        tkinter.Button(root, text=key, width=120, padx=3, pady=3, bd=5, font=('Helvetica', 12, 'bold'),
                       activebackground="#ffffff", activeforeground="#000000", relief='raised',
                       command=key_command).grid(row=6, columnspan=16)

    columns += 1
    if columns > 15 and rows == 2:
        columns = 0
        rows += 1

    if columns > 15 and rows == 3:
        columns = 0
        rows += 1

root.mainloop()

例如:

def key_input(value):
    if value == "-":
        entry.insert(tkinter.END, "Hello World")
    elif value == " Space ":
        entry.insert(tkinter.END, ' This is space')
    elif value == "Tab":
        entry.insert(tkinter.END, ' function key input ')

推荐阅读