为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 for 循环按名称修改变量?

如何使用 for 循环按名称修改变量?

明月笑刀无情 2022-10-18 19:56:37
b1 = Button(win,padx = 70,pady = 70,bg = "gray", command = lambda: click(b1))b2 = Button(win,padx = 70,pady = 70, command = lambda: click(b2))b3 = Button(win,padx = 70,pady = 70, command = lambda: click(b3))b4 = Button(win,padx = 70,pady = 70, command = lambda: click(b4))b5 = Button(win,padx = 70,pady = 70, command = lambda: click(b5))b6 = Button(win,padx = 70,pady = 70, command = lambda: click(b6))b7 = Button(win,padx = 70,pady = 70, command = lambda: click(b7))b8 = Button(win,padx = 70,pady = 70, command = lambda: click(b8))b9 = Button(win,padx = 70,pady = 70, command = lambda: click(b9))for n in range(10):    bn.configure(text=="something") #To modify all buttons with loop如何使用for循环动态修改按钮的名称?
查看完整描述

2 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

如果b1-b2在您的全局范围内定义并且您想通过它们的名称动态访问它们,您可以使用gloabls():


b1 = Button(win,padx = 70,pady = 70,bg = "gray", command = lambda: click(b1))

b2 = Button(win,padx = 70,pady = 70, command = lambda: click(b2))

b3 = Button(win,padx = 70,pady = 70, command = lambda: click(b3))

b4 = Button(win,padx = 70,pady = 70, command = lambda: click(b4))

b5 = Button(win,padx = 70,pady = 70, command = lambda: click(b5))

b6 = Button(win,padx = 70,pady = 70, command = lambda: click(b6))

b7 = Button(win,padx = 70,pady = 70, command = lambda: click(b7))

b8 = Button(win,padx = 70,pady = 70, command = lambda: click(b8))

b9 = Button(win,padx = 70,pady = 70, command = lambda: click(b9))


for n in range(1,10):

    bn = globals()["b{}".format(i)]

    bn.configure(text=="something") #To modify all buttons with loop


查看完整回答
反对 回复 2022-10-18
?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

创建一个按钮字典,即


dict_button = {}


for n in range(10):

     dict_button['b'+ str(n)].configure(text=="something")

并将字典中的按钮保持为


dict_button['b1'] = Button(win,padx = 70,pady = 70,bg = "gray", command = lambda: click(b1))



查看完整回答
反对 回复 2022-10-18
  • 2 回答
  • 0 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信