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

2024-05-16 21:58:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究这个比较两个字符串的单个字符的短代码。在第一次运行之后,当我更改entrybox中的字符串时,我希望替换之前创建的标签,而不是创建新的标签。我已经尝试过使用StringVar(),但它似乎不起作用。(如果有用的话,我将使用Python2.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()

Tags: oftextinappgetlenifcount
1条回答
网友
1楼 · 发布于 2024-05-16 21:58:11

仅在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) + " %"))

相关问题 更多 >