Home > Mobile >  Copy a label on tkinter and change the text on button click?
Copy a label on tkinter and change the text on button click?

Time:05-01

I have some program of this kind of type:

from tkinter import *

def apply_text(lbl_control):
    lbl_control['text'] = "This is some test!"

master = Tk()

lbl = Label(master)
btn = Button(master, text="apply", command=lambda: apply_text(lbl))


lbl.pack()
btn.pack()

mainloop()

My aim now is to copy the text of the label lbl itself without any ability to change it. I tried the following way to solve the problem:

from tkinter import *

def apply_text(lbl_control):
    lbl_control.insert(0, "This is some test!")

master = Tk()

lbl = Entry(master, state="readonly")
btn = Button(master, text="apply", command=lambda: apply_text(lbl))


lbl.pack()
btn.pack()

mainloop()

because of state = "readonly" it is not possible to change the text insert of lbl anymore. For that reason nothing happens if I click on the button apply. How can I change it?

CodePudding user response:

There is a simple way to do that simple first change the state of entry to normal, Then insert the text, and then change the state back to readonly.

from tkinter import *

def apply_text(lbl_control):
    lbl_control['state'] = 'normal'
    lbl_control.delete(0,'end')
    lbl_control.insert(0, "This is some test!")
    lbl_control['state'] = 'readonly'

master = Tk()

lbl = Entry(master, state="readonly")
btn = Button(master, text="apply", command=lambda: apply_text(lbl))


lbl.pack()
btn.pack()

mainloop()

There is another way to do this using textvariable.
Code:(Suggested)

from tkinter import *

def apply_text(lbl_control):
    eText.set("This is some test.")

master = Tk()

eText = StringVar()
lbl = Entry(master, state="readonly",textvariable=eText)
btn = Button(master, text="apply", command=lambda: apply_text(lbl))


lbl.pack()
btn.pack()

mainloop()
  • Related