Python 将变量的内容复制到剪贴板

Python copy to clipboard the content of a variable

我有一个变量,用于存储用户在对话框中键入的文本。 我需要复制此文本,然后将其粘贴到另一个字段(以进行搜索)

我试过 pyperclip,但它只适用于纯文本,不适用于变量。这是对话框的代码,e 是我的变量。

from tkinter import *
master = Tk()
e = Entry(master)
e.pack()

e.focus_set()


def callback():
    print(e.get())  # This is the text I want to use later


b = Button(master, text="insert", width=10, command=callback)
b.pack()


mainloop()

您需要创建 tkinter 字符串来存储此值,我已将其包含在下面的代码中。

from tkinter import *
master = Tk()

estring = StringVar(master)

e = Entry(master, textvariable = estring,)
e.pack()

e.focus_set()




def callback():
    print(estring.get())  # This is the text I want to use later


b = Button(master,  text="insert", width=10, command=callback)
b.pack()


mainloop()

下面是使用 pyperclip 将输入文本复制到剪贴板的示例。

from tkinter import *
import pyperclip

master = Tk()

estring = StringVar(master)

e = Entry(master, textvariable = estring,)
e.pack()

e.focus_set()


def callback():
    pyperclip.copy(estring.get())

b = Button(master,  text="copy", width=10, command=callback)
b.pack()


mainloop()

输入文本并按下复制按钮后,文本现在已在剪贴板上。

这在您的上下文中不起作用?

import pyperclip

test = "Hugo"
pyperclip.copy(test)
print(pyperclip.paste())