In python's tkinter, how can I make a Label such that you can select the text with the mouse?

StackOverflow https://stackoverflow.com/questions/1602106

  •  05-07-2019
  •  | 
  •  

Question

In python's tkinter interface, is there a configuration option that will change a Label such that you can select the text in the Label and then copy it to the clipboard?

EDIT:

How would you modify this "hello world" app to provide such functionality?

from Tkinter import *

master = Tk()

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

mainloop()
Was it helpful?

Solution

The easiest way is to use a disabled text widget with a height of 1 line:

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

You could use an entry widget in a similar manner.

OTHER TIPS

Made some changes to the above code:

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

The relief needs to be flat in order for it to look like an ordinary part of the display. :)

You can make texts which are selectable using either Text or Entry I really find both useful, using text can be really helpful! Here I show you a code of 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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top