在python的tkinter中,如何制作一个Label,以便用鼠标选择文本?

Ros*_*ers 12 python tkinter

在python的tkinter界面中,是否有一个配置选项可以更改Label,以便您可以选择Label中的文本然后将其复制到剪贴板?

编辑:

你会如何修改这个"hello world"应用来提供这样的功能?

from Tkinter import *

master = Tk()

w = Label(master, text="Hello, world!")
w.pack()

mainloop()
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 10

最简单的方法是使用高度为1行的禁用文本小部件:

from Tkinter import *

master = Tk()

w = Text(master, height=1, borderwidth=0)
w.insert(1.0, "Hello, world!")
w.pack()

w.configure(state="disabled")

# if tkinter is 8.5 or above you'll want the selection background
# to appear like it does when the widget is activated
# comment this out for older versions of Tkinter
w.configure(inactiveselectbackground=w.cget("selectbackground"))

mainloop()
Run Code Online (Sandbox Code Playgroud)

您可以以类似的方式使用条目小部件.

  • 对我来说,`state ="disabled"`甚至不让我选择要复制的文本.将它设置为`state ="readonly"`实际上有效. (2认同)

小智 5

对上面的代码做了一些修改:

from tkinter import *

master = Tk()

w = Text(master, height=1)
w.insert(1.0, "Hello, world!")
w.pack()



# if tkinter is 8.5 or above you'll want the selection background
# to appear like it does when the widget is activated
# comment this out for older versions of Tkinter
w.configure(bg=master.cget('bg'), relief="flat")

w.configure(state="disabled")

mainloop()
Run Code Online (Sandbox Code Playgroud)

浮雕需要平坦,才能看起来像显示器的普通部分。:)


Jai*_*dee 5

您可以使用其中之一制作可选择的文本,Text或者Entry 我真的发现两者都很有用,使用文本真的很有帮助!这里我给大家展示一个Entry的代码:

from tkinter import *
root = Tk()
data_string = StringVar()
data_string.set("Hello World! But, Wait!!! You Can Select Me :)")
ent = Entry(root,textvariable=data_string,fg="black",bg="white",bd=0,state="readonly")
ent.pack()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)