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的下标就可对按钮对象进行操作了


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM