2

I am having difficulty updating a python Tkinter frame. I draw the frame with some labels and text fields, when a person presses a button, I want to do some calculations and update the labels and text fields. I can print the data to my stdout, but I cannot get the Tk screen to update. How can I get the countFld to display an updated value?

class Application(Frame):

    def __init__(self):
      self.root = Tk()
      Frame.__init__(self, self.root)
      self.count = 0
      self.createWidgets()

  def createWidgets(self):
      self.countFrame = Frame(self, bd=2, relief=RIDGE)
      Label(self.countFrame, text='Count:').pack(side=LEFT, padx=5)
      self.countFld = IntVar()
      Label(self.countFrame, text=str(self.count)).pack(side=RIGHT, padx=5)
      self.countFld.set(self.count)
      self.countFrame.pack(expand=1, fill=X, pady=10, padx=5)

      self.CNTBTN = Button(self)
      self.CNTBTN["text"] = "UPDATE"
      self.CNTBTN["fg"]   = "red"
      self.CNTBTN["command"] =  self.update_count 
      self.CNTBTN.pack({"side": "left"})

  def update_count(self):
      self.count = self.count + 1
      print "Count = %" % self.count #prints correct value
      self.countFld.set(self.count)  #Does not update display
codingJoe
  • 4,713
  • 9
  • 47
  • 61

2 Answers2

2

Your problem is that you do not attach the Variable to the widget. In addition you need to use a StringVar, as the Label Widget operates on Strings and not Ints.

Try something like:

self.countStr = StringVar()
self.countStr.set(str(self.count))
Label(self.countFrame, textvariable=self.countStr).pack(side=RIGHT, padx=5)

Tk updates the display when the eventloop is idle. So you need to re-enter the event loop after you set the new value.

schlenk
  • 7,002
  • 1
  • 25
  • 29
1

You should try destroying the label itself and making it again in the code with the updated text and use self.root.update()

Waterbin
  • 23
  • 5