Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

python - Generate Tkinter Buttons dynamically

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)

If boardWidth is 5, though I get buttons labelled 1 to 5, when clicked they all do Board.playColumn(5, 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

Update

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...