codingJoe
codingJoe

Reputation: 4943

Updating a python Tkinter frame

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

Upvotes: 2

Views: 9257

Answers (2)

Waterbin
Waterbin

Reputation: 23

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

Upvotes: 1

schlenk
schlenk

Reputation: 7247

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.

Upvotes: 2

Related Questions