繁体   English   中英

如何在Python Tkinter GUI的“标签”小部件中显示更新的值?

[英]How do I show updated values in the 'label' widget in Python Tkinter GUI?

我有一个基于python Tkinter的GUI,我希望在单击“读取”按钮时显示几个变量的值。 理想情况下,这应该发生在显示更新变量的窗口中的某个帧中,而不会干扰具有其他功能的其他GUI小部件。

我遇到的问题是这样 - 每次我点击“读取”时,更新的变量都列在旧变量的正下方,而不是在该位置覆盖。 我似乎对标签的工作以及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时(单击读取按钮时),它都会附加到上一个显示。

PS - 如果有更好的方式来显示数据,除了标签小部件,那么请建议。

问题是每次运行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()

我正在回答我自己的问题,修改了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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM