如何更新Tkinter中的标签,StringVar()不起作用

时间:2014-12-14 12:30:16

标签: python python-2.7 tkinter label

我正在研究这个比较两个字符串的单个字符的短代码。在第一次运行之后,当我更改entryBoxes中的字符串时,我想替换之前创建的标签,而不是创建一个新标签。我已经尝试过使用StringVar(),但它似乎无法正常工作。 (如果它有用,我使用的是Python 2.7.6)。你能给我一个提示吗?

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

1 个答案:

答案 0 :(得分:4)

仅在for循环外创建一次标签,并使用StringVar修改其值。它看起来像这样:

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

然后在函数内的for循环中:

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