En tkinter de python, ¿cómo puedo hacer una etiqueta que permita seleccionar el texto con el mouse?

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

  •  05-07-2019
  •  | 
  •  

Pregunta

En la interfaz tkinter de python's, ¿hay alguna opción de configuración que cambie una etiqueta de modo que pueda seleccionar el texto en la etiqueta y luego copiarla al portapapeles?

EDITAR:

¿Cómo modificarías este " hola mundo " aplicación para proporcionar dicha funcionalidad?

from Tkinter import *

master = Tk()

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

mainloop()
¿Fue útil?

Solución

La forma más sencilla es usar un widget de texto deshabilitado con una altura de 1 línea:

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

Podrías usar un widget de entrada de una manera similar.

Otros consejos

Hice algunos cambios en el código anterior:

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

El relieve debe ser plano para que se vea como una parte normal de la pantalla. :)

Puede hacer textos que se pueden seleccionar utilizando Text o Entry Realmente encuentro ambos útiles, usar texto puede ser realmente útil! Aquí te muestro un código de entrada:

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()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top