Dynamically create Tkinter buttons

I want to create n number of Tkinter buttons that 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, although I get buttons labeled 1-5, when pressed they all do Board.playColumn (5, Board.getCurrentPlayer ()).

I need the first button to create Board.playColumn (1, Board.getCurrentPlayer ()), the second for Board.playColumn (2, Board.getCurrentPlayer ()), etc.

Thanks for any help!

+3
source share
3 answers

I think the problem is that it lambdaselects the final value iafter the loop ends for. This should fix this (not verified):

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)

Refresh

, lambda , i , , i , .

+10

, lambda , lambda . , , , ... , lambdas i.

factory, :

import Tkinter as tk

def callbackFactory(b, n):
    def _callback():
        return b.playColumn(n, b.getCurrentPlayer())
    return _callback

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

- lambda , :

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

"", , ? :

for ID_ in curseur.execute("SELECT ID FROM client"):
    Label(FrameMain , text=ID_, font=('Arial', 12, 'bold')).grid(row=ID_, column=7)
    Button(FrameMain, text='Compléter', font=('Arial',14), cursor='hand2', command=lambda : get_id(ID_)).grid(row=c_ID.get(),column=6, sticky='e')
    c_ID.set(c_ID.get() + 1)
    print(ID_)


def get_id(ID):
    my_ID = ID - 1
    print(my_ID)

, , : TypeError: unsupported operand type(s) for -: 'tuple' and 'int'

0

Source: https://habr.com/ru/post/1776031/


All Articles