3

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

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

3 回答 3

2

您将希望传递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

于 2017-10-18T19:11:35.633 回答
1

您需要删除以下行,因为它会覆盖您使用键盘复制的内容。

pyperclip.copy('The text to be copied to the clipboard.')

例如,我复制了你的问题标题,下面是我将它粘贴到 python shell 中的方法:

>>> import pyperclip 
>>> pyperclip.paste() 
'How do I paste the copied text from keyboard in python\n\n'
>>> 
于 2017-10-18T19:03:05.483 回答
0

如果您已经tkinter在代码中使用,那么您所需要的只是剪贴板中的内容。然后tkinter有一个内置的方法来做到这一点。

import tkinter as tk
root = tk.Tk()
spam = root.clipboard_get()

要将复制的文本添加到tkinter条目/文本框中,可以使用tkinter变量:

var = tk.StringVar()
var.set(spam)

并将该变量链接到 Entry 小部件。

box = tk.Entry(root, textvariable = var)
于 2017-10-19T17:02:17.260 回答