Nel tkinter di Python, come posso creare un'etichetta in modo da poter selezionare il testo con il mouse?

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

  •  05-07-2019
  •  | 
  •  

Domanda

Nell'interfaccia tkinter di python, esiste un'opzione di configurazione che cambierà un'etichetta in modo tale che tu possa selezionare il testo nell'etichetta e quindi copiarlo negli appunti?

EDIT:

Come modificheresti questo " ciao mondo " app per fornire tale funzionalità?

from Tkinter import *

master = Tk()

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

mainloop()
È stato utile?

Soluzione

Il modo più semplice è utilizzare un widget di testo disabilitato con un'altezza di 1 riga:

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

È possibile utilizzare un widget di immissione in modo simile.

Altri suggerimenti

Apportate alcune modifiche al codice sopra:

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

Il rilievo deve essere piatto in modo che appaia come una parte ordinaria del display. :)

Puoi creare testi selezionabili usando Text o Entry Trovo davvero entrambi utili, usare il testo può essere davvero utile! Qui ti mostro un codice di ingresso:

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()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top