【问题标题】:Disabling Button created in for loop tkinter禁用在 for loop tkinter 中创建的按钮
【发布时间】:2020-03-04 19:16:43
【问题描述】:
for bear in self.bears:
                 button=tk.Button(self,text=polar.spec(),command=lambda 
                          id=polar.spec:self.polar_ad(id))
                 button.grid(row=_r,column=_c,sticky=W+E+N+S)
                 _row+=1

您好,所以我在 for 循环中创建了许多按钮,但是当我单击按钮时,我希望能够禁用它。如果按钮是单独创建的,那么我可以使用

button["state"]="disabled"

但是我怎样才能通过使用按钮的 id 来使用它呢?谢谢

【问题讨论】:

标签: python python-3.x tkinter


【解决方案1】:

我会在创建时将按钮添加到数组中,然后循环遍历数组并检查 id。

buttons = []
for bear in self.bears:
   btn = tk.Button(self,text=polar.spec(),command=lambda id=polar.spec:self.polar_ad(id))
   btn.grid(row=_r,column=_c,sticky=W+E+N+S)
   buttons.append(btn)
   _id += 1
   _row += 1

然后检查按钮 ID

for b in buttons:
   if b.id == <id_of_button_press>:
       b['state'] = "disabled"

我不确定您是否可以通过这种方式获取按钮的 id,但主体应该是有意义的。

【讨论】:

    【解决方案2】:
    buttons=[]
    num=0
    for bear in self.bears:
                     button=tk.Button(self,text=polar.spec(),command=lambda 
                             id=polar.spec,index=num:self.polar_ad(id,index))
                     button.grid(row=_r,column=_c,sticky=W+E+N+S)
                     num+=1
                     _row+=1
    

    然后

    self.polar(id,index):
                     buttons[index]["state"]="disabled"
    

    感谢您的想法确实帮助我走上了正确的轨道@Uuuuuumm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      相关资源
      最近更新 更多