Python Tkinter: 如何在按钮的事件处理程序中更改其他按钮的文本

文章讲述了作者在使用Tkinter创建按钮矩阵时遇到的问题,即如何在单击一个按钮后更改其他按钮的文本。通过调整代码存储按钮对象的方式和使用事件处理程序,解决了在事件处理程序外部更改按钮文本的问题。
摘要由CSDN通过智能技术生成

在使用 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

这样就可以在按钮的事件处理程序中更改其他按钮的文本了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值