Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading