【问题标题】:How do I show updated values in the 'label' widget in Python Tkinter GUI?如何在 Python Tkinter GUI 的“标签”小部件中显示更新的值?
【发布时间】:2014-06-16 19:55:01
【问题描述】:

我有一个基于 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 - 如果有更好的方式来显示数据,除了标签小部件,那么请提出建议。

【问题讨论】:

    标签: python user-interface tkinter


    【解决方案1】:

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

    【讨论】:

    • 这会在最后一行出现错误“UnboundLocalError: local variable 'labelR2s' referenced before assignment”。
    • 哦,对了 - 您需要将 labelR2s 声明为全局变量(更新了答案)。顺便说一句,使用类结构通常比使用全局变量更好。
    【解决方案2】:

    我正在通过修改 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()
    

    【讨论】:

      猜你喜欢
      • 2010-12-27
      • 2019-04-23
      • 2011-03-29
      • 1970-01-01
      • 2017-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      相关资源
      最近更新 更多