如何在Python Tkinter GUI中显示'label'小部件的更新值?

1 投票
2 回答
1618 浏览
提问于 2025-04-18 09:59

我有一个基于Python Tkinter的图形界面,想在点击“读取”按钮时显示几个变量的值。理想情况下,这些值应该在窗口的某个框架里更新显示,而不影响其他的界面组件,因为它们有其他的功能。

我遇到的问题是:每次我点击“读取”时,更新的变量会在旧变量的下面显示,而不是覆盖在原来的位置。我好像对标签的工作原理,以及padx和pady(标签的位置设置)理解得不太对。我把代码贴在下面。请问应该怎么做才能让之前的数据被清除,然后在同一个位置显示新数据呢?

def getRead():
    #update printList
    readComm()
    #update display in GUI
    i=0
    while i < (len(printList)):
        labelR2=Tk.Label(frameRead, text=str(printList[i]))
        labelR2.pack(padx=10, pady=3)
        i=i+1

frameRead=Tk.Frame(window)
frameRead.pack(side=Tk.TOP)
btnRead = Tk.Button(frameRead, text = 'Read', command= getRead)
btnRead.pack(side = Tk.TOP)  

window.mainloop()

上面的代码成功地将printList中的元素以一列的形式显示出来。但是,每次调用getRead(也就是点击读取按钮时),它会在之前的显示内容上继续添加。

另外,如果有比标签组件更好的显示数据的方法,请推荐一下。

2 个回答

2

问题在于每次你运行 getRead 时,都会创建一组新的标签。听起来你想做的是更新现有标签的文本,而不是创建新的标签。下面是一个实现这个目标的方法:

labelR2s = []

def getRead():
    global labelR2s
    #update printList
    readComm()
    #update display in GUI

    for i in range(0, len(labelR2s)):               # Change the text for existing labels
        labelR2s[i].config(text=printList[i])

    for i in range(len(labelR2s), len(printList)):  # Add new labels if more are needed
        labelR2s.append(Tk.Label(frameRead, text=str(printList[i])))
        labelR2s[i].pack(padx=10, pady=3)

    for i in range(len(printList), len(labelR2s)):  # Get rid of excess labels
        labelR2s[i].destroy()
    labelR2s = labelR2s[0:len(printList)]

    window.update_idletasks()
1

我在回答我自己的问题,同时对Brionius给出的答案进行了修改,因为他的答案出现了引用错误。下面的代码对我来说运行得很好。

labelR2s=[]
def getRead():
    #update printList
    readComm()
    #update display in GUI

    for i in range(0, len(printList)):               # Change the text for existing labels
        if (len(printList)>len(labelR2s)):           # this is the first time, so append
            labelR2s.append(Tk.Label(frameRead, text=str(printList[i])))
            labelR2s[i].pack(padx=10, pady=3)
        else:
            labelR2s[i].config(text=printList[i])    # in case of update, modify text

    window.update_idletasks()

撰写回答