2017-10-18 630 views
1

如果我執行此代碼,它工作正常。但如果我使用鍵盤複製某些東西(Ctrl + C),那麼如何將剪貼板上的文本粘貼到任何輸入框或Python中的文本框?如何粘貼Python中鍵盤複製的文本

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

回答

0

您需要刪除行:因爲它會覆蓋您在使用鍵盤複製什麼

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' 
>>> 
0

你會希望通過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

0

如果你已經在你的代碼中使用tkinter,所有你需要的是在剪貼板中的內容。然後tkinter有一個內置的方法來做到這一點。

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

要在tkinter輸入/文本框添加複製的文字,你可以使用一個tkinter變量:

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

,並且這個變量鏈接到輸入構件。

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