Francesca Galante
Francesca Galante

Reputation: 43

How to update a label in Tkinter, StringVar() not working

I am working on this short code that compares the single characters of two strings. After the first running, when I change the strings in the entryBoxes,I would like to replace the label created before, instead of creating a new one. I have already tried with StringVar() but it seems not working. (If it can be useful I'm using Python 2.7.6). Could you please give me a hint?

from Tkinter import *

app = Tk()
app.geometry('450x300')


labelTF = Label(app, text="Insert sequence of TF").pack()
eTF = Entry(app, width=50)
eTF.pack()
eTF.focus_set()


labelSpazio = Label(app, text="\n").pack()

labelResultedSequence = Label(app, text="Insert sequence of ResultedSequence").pack()
eResultedSequence = Entry(app, width=50)
eResultedSequence.pack()
eResultedSequence.focus_set()

def prova():
    count = 0
    uno = eTF.get().lower()
    due = eResultedSequence.get().lower()
    if len(uno)==len(due):
            for i in range(0,len(uno)):
                if uno[i] == due[i]:
                    if uno[i] in ("a", "c","g","t"):
                        count = count + 1 
                if uno[i] == "r" and due[i] in ("a", "g"):
                    count = count + 1 
                if uno[i] == "y" and due[i] in ("t", "c"):
                    count = count + 1 
            percentage = int(float(count)/float(len(uno))*100)
            labelSpazio = Label(app, text="\n").pack()
            mlabel3=Label(app,text= "The final similarity percentage is: "+(str(percentage) + " %")).pack()

    if len(uno)!=len(due):
        mlabel2 = Label(app,text="The length of the sequences should be the same").pack()



b = Button(app, text="get", width=10, command=prova)
b.pack()

mainloop()

Upvotes: 3

Views: 12685

Answers (1)

elyase
elyase

Reputation: 40973

Create the labels only once outside of the for loop and use a StringVar to modify its value. It would look like this:

# initialization
app = Tk()
label3text = StringVar()
mlabel3 = Label(app, textvariable=label3text, width=100)
mlabel3.pack()

Then in the for loop inside your function:

label3text.set("The final similarity percentage is: "+(str(percentage) + " %"))

Upvotes: 4

Related Questions