How do I paste the copied text from keyboard in python

笑着哭i 提交于 2020-02-05 05:13:04

问题


If I execute this code, it works fine. But if I copy something using the keyboard (Ctrl+C), then how can I paste the text present on clipboard in any entry box or text box in python?

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

回答1:


You will want to pass pyperclip.paste() the same place you would place a string for your entry or text widget inserts.

Take a look at this example code.

There is a button to copy what is in the entry field and one to paste to entry field.

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()

Alternatively you could just do Ctrl+V :D




回答2:


You need to remove the line:

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

Because it overrides what you are copied using the keyboard.


For example, I copied you question's title, and here's how I pasted into python shell:

>>> import pyperclip 
>>> pyperclip.paste() 
'How do I paste the copied text from keyboard in python\n\n'
>>> 



回答3:


If you're already using tkinter in your code, and all you need is the content in the clipboard. Then tkinter has an in-built method to do just that.

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

To add the copied text in a tkinter Entry/Textbox, you can use a tkinter variable:

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

And link that variable to the Entry widget.

box = tk.Entry(root, textvariable = var)


来源:https://stackoverflow.com/questions/46817290/how-do-i-paste-the-copied-text-from-keyboard-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!