Sunday, 15 September 2013

Python Tkinter: Changing other button's text from event handler of one button

Python Tkinter: Changing other button's text from event handler of one button

I have the following problem when using tkinter to create a very simple
window containing a matrix of buttons: When one of the buttons is clicked,
the event handler changes the text of that button using the configure
method on the button widget. This works. But I also want to change the
text in one of the other buttons, which does not work. The method I use is
that on creating the button, I store the object returned by the Button
method before I use the grid geometry manager to place it. This object
looks like ".123456789L" when printed and seems to be a pointer to the
widget. I also use configure on this to change the button text. But
somehow it seems to be wrong, because it works sometimes, and most of the
times not. There's unfortunately no error message, just nothing happens
when calling configure. I checked and it seems to be the correct pointer
to the widget. Do I have to use a special way to affect a widget other
that the one that called the event handler? These are the relevant parts
of the code:
# CREATING THE BUTTONS:
buttons={} # global
for i in range(3):
for j in range(3):
button = Tkinter.Button(self,text='foo')
buttons[button]=(i,j)
button.grid(column=j,row=i)
button.bind( "<Button-1>", self.OnButtonClick )
# CHANGING BUTTONS:
def find_button(i,j):
"""Return the pointer to the other button to be changed when a button has
been clicked."""
for button,key in buttons.items():
if key==(i,j): return button
def OnButtonClick(self,event):
print "You clicked the button",buttons[event.widget]
i,j=buttons[event.widget]
old_button=find_button(i,j) # This is simplified, I don't actually pass
i,j, but other values. But I checked this and it returns the reference to
the correct button. But this simplified version works the same way, just
assume a different button that the one pressed would be returned.
old_button.configure(text = 'blabla') # THIS DOES NOT WORK
event.widget.configure(text = 'something') # THIS WORKS

No comments:

Post a Comment