加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 动态生成Tkinter按钮

发布时间:2020-12-20 12:17:25 所属栏目:Python 来源:网络整理
导读:我想生成n个不同的Tkinter按钮.我有这个代码: import Tkinter as tkfor i in range(boardWidth): newButton = tk.Button(root,text=str(i+1),command=lambda: Board.playColumn(i+1,Board.getCurrentPlayer())) Board.boardButtons.append(newButton) 如果b
我想生成n个不同的Tkinter按钮.我有这个代码:

import Tkinter as tk

for i in range(boardWidth):
    newButton = tk.Button(root,text=str(i+1),command=lambda: Board.playColumn(i+1,Board.getCurrentPlayer()))
    Board.boardButtons.append(newButton)

如果boardWidth是5,虽然我得到标记为1-5的按钮,但是当它们单击时它们都会执行Board.playColumn(5,Board.getCurrentPlayer()).

我需要第一个按钮来执行Board.playColumn(1,Board.getCurrentPlayer()),第二个按钮来执行Board.playColumn(2,Board.getCurrentPlayer())等等.

谢谢你的帮助!

解决方法

我认为问题是在for循环结束后lambda正在拾取i的最终值.这应该解决(未经测试):

import Tkinter as tk

for i in range(boardWidth):
    newButton = tk.Button(root,command=lambda j=i+1: Board.playColumn(j,Board.getCurrentPlayer()))
    Board.boardButtons.append(newButton)

更新

顺便说一下,这是通过向lambda函数添加一个参数来实现的,该参数的默认值是在循环中创建每个函数时从i的值计算的,而不是通过闭包在其中表达式时返回i的最终值稍后执行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读