在使用 Tkinter 创建包含按钮矩阵的简单窗口时,我遇到以下问题:当单击其中一个按钮时,事件处理程序使用按钮控件上的配置方法更改该按钮的文本。这种方法有效。但是我还想更改其他按钮中的文本,但这不起作用。我使用的方法是在创建按钮时,在使用网格几何管理器将其放置之前,存储 Button 方法返回的对象。打印此对象时,它看起来像 “.123456789L”,似乎是指向小部件的指针。我还在此使用 configure 来更改按钮文本。但不知何故,这似乎是错误的,因为它有时有效,而大部分时间都不起作用。不幸的是没有错误消息,只是在调用 configure 时没有任何发生。我检查过,它似乎是指向小部件的正确指针。我是否必须使用一种特殊的方法来影响调用事件处理程序以外的小部件?以下是代码的相关部分:
# 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
2、解决方案
一种解决方法是在创建按钮时,将按钮对象存储在字典中,其中键是按钮的行列索引,值是按钮对象。在按钮的事件处理程序中,我们可以使用行列索引来查找要更改的按钮,然后使用 configure 方法更改其文本。
# CREATING THE BUTTONS:
buttons={} # global
for i in range(3):
for j in range(3):
button = Tkinter.Button(self,text='foo')
buttons[(i,j)]=button
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."""
return buttons[(i,j)]
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
这样就可以在按钮的事件处理程序中更改其他按钮的文本了。