不明白如何从CTkLabel复制数据

问题描述 投票:0回答:2

如何从自定义 tkinter 标签复制信息?

我制作了密码管理器,想从标签中选择文本并复制它,但不能。我使用了 pyperclip 但这不是我需要的。直接想选择文字复制即可!

import customtkinter
import tkinter
import pyperclip

from cryptography.fernet import Fernet

customtkinter.set_appearance_mode("dark")

app = customtkinter.CTk()
app.geometry("400x300")

def copy():
    pyperclip.copy(lbl1.text)
    lbl2.configure(text="Successfully")


lbl1 = customtkinter.CTkLabel(text="Website")
lbl1.pack()

lbl2 = customtkinter.CTkLabel(text="")
lbl2.pack()

btn1 = customtkinter.CTkButton(text="Copy", command=copy)
btn1.pack()


app.mainloop()
python tkinter customtkinter
2个回答
1
投票

首先需要通过

master
指定父窗口。然后你就可以通过
.cget
属性来做到这一点。

import customtkinter

customtkinter.set_appearance_mode("dark")

def copy():
    copied_var = lbl1.cget("text")
    lbl2.configure(text="Successfully")

app = customtkinter.CTk()
app.geometry("400x300")


lbl1 = customtkinter.CTkLabel(master=app, text="Website")
lbl1.pack()

lbl2 = customtkinter.CTkLabel(master=app, text="")
lbl2.pack()

btn1 = customtkinter.CTkButton(master=app, text="Copy", command=copy)
btn1.pack()

app.mainloop()

您必须仔细查看此页面:https://github.com/TomSchimansky/CustomTkinter/wiki


0
投票

我也在制作密码管理器!
我发现从标签复制文本的方法是在要从中复制文本的标签上使用 .bind() 方法。 (我知道您正在尝试复制到剪贴板,因为您正在使用 pyperclip)

import customtkinter as ctk

text_label = ctk.CTkLabel(self, text="Your_Text", cursor="hand2")
text_label.pack()
text_label.bind("<Button-1>", self.on_click)

def on_click(self):
    text = text_label.cget("text")
    self.clipboard_clear()
    self.clipboard_append(text)

希望您发现这很有用。
Pd:您需要在 CTkLabel 上添加父窗口,在您的示例中为“app”

© www.soinside.com 2019 - 2024. All rights reserved.