Python-Tkinter 使用for循环生成列表式Button及函数调用

Tkinter是轻量级的图形化界面,在使用中我们可能遇到需要生成一串Button按钮的情况,如图:

如果一个一个操作就太麻烦了,但我们可以通过for循环列表的形式来实现
来看看以下例子:

from tkinter import *

def printf_button(f):

    print('press button:',f)

if __name__ == '__main__':

    root = Tk()

    ButtonList = [0,0,0,0,0,0,0]#创建储存按钮对象的列表
    ValueList = ['1','2','3','4','5','6','7']#创建按钮文字的列表
    sx = 20

    for i in range(0,7):
        ButtonList[i] = Button(width=6,height=2,text=ValueList[i],command=lambda f=ValueList[i]:printf_button(f))
        ButtonList[i].place(x=sx,y=20)
        sx+=60

    root.mainloop()

执行以上代码后,我们得到如下效果:

至此,我们成功实现生成列表式Button按钮
通过访问ButtonList的下标就可对按钮对象进行操作了

posted @ 2021-04-10 10:25  Evan_Lai  阅读(1674)  评论(2编辑  收藏  举报