如何在 python 中粘贴从键盘复制的文本

新手上路,请多包涵

如果我执行这段代码,它工作正常。但是,如果我使用键盘( Ctrl + C )复制某些内容,那么如何将剪贴板上的文本粘贴到 python 中的任何输入框或文本框中?

 import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()

原文由 divyjot singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 943
1 个回答

您将要传递 pyperclip.paste() 与放置用于条目或文本小部件插入的字符串的相同位置。

看看这个示例代码。

有一个按钮可以复制输入字段中的内容,还有一个按钮可以粘贴到输入字段。

 import tkinter as tk
from tkinter import ttk
import pyperclip

root = tk.Tk()

some_entry = tk.Entry(root)
some_entry.pack()

def update_btn():
    global some_entry
    pyperclip.copy(some_entry.get())

def update_btn_2():
    global some_entry
    # for the insert method the 2nd argument is always the string to be
    # inserted to the Entry field.
    some_entry.insert(tk.END, pyperclip.paste())

btn = ttk.Button(root, text="Copy to clipboard", command = update_btn)
btn.pack()

btn2 = ttk.Button(root, text="Paste current clipboard", command = update_btn_2)
btn2.pack()

root.mainloop()

或者你可以只做 Ctrl + V :D

原文由 Mike - SMT 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题