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

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循环动态修改按钮的名称?


明月笑刀无情
浏览 103回答 2
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

沧海一幻觉

创建一个按钮字典,即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))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python