本文介绍了Tkinter的生成动态按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要生成Tkinter的按钮,它做不同的事情的施氮量。我有这个code:

I want to generate n amount of Tkinter buttons which do different things. I have this code:

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())。

If boardWidth is 5, though I get buttons labelled 1-5, when clicked they all do Board.playColumn(5, Board.getCurrentPlayer()).

我需要的第一个按钮做Board.playColumn(1,Board.getCurrentPlayer()),所述第二做Board.playColumn(2,Board.getCurrentPlayer())等。

I need the first button to do Board.playColumn(1, Board.getCurrentPlayer()), the second to do Board.playColumn(2, Board.getCurrentPlayer()) and so on.

感谢您的帮助!

推荐答案

我觉得问题是,的λ正在回升的终值循环结束后。这应该解决这个问题(未经测试):

I think the problem is that the lambda is picking up the final value of i after the for loop ends. This should fix that (untested):

import Tkinter as tk

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

更新

顺便说一句,这通过添加参数与值计算的默认值的λ功能I 当它被创建,而不是通过关闭再参照 I 终值时,在它的前pression后执行。

BTW, this worked by adding an argument to the lambda function with a default value calculated from the value of i when it was created rather than referring back to the final value of i through a closure when the expression within it executes later.

这篇关于Tkinter的生成动态按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:50