Home > Software engineering >  How do I use a for loop counter as the input to a function?
How do I use a for loop counter as the input to a function?

Time:12-10

I am having an issue with a Python program I have made. It involves the tkinter module and the for loop.

Here is my code:

from tkinter import Button

def action(n):
    print(n)
    
for num in range(1, 6):
    Button(text=str(num), command=lambda: action(n=num)).pack()

What does it do?

5 buttons are created and the text (in the buttons) increases by 1 every time, so it looks like:

This image shows the Tkinter window

In line 1, I import the Button class from the tkinter module.

In lines 3-4, I create a subroutine called 'action' that takes an input of 'n' and outputs it to the console.

In line 6, a for loop is used to iterate over values in a range from 1, to 5 (hence why 6 is used).

In line 7, I create a button from the Button tkinter class that has text of the current 'num'. A command is added to perform the 'action' subroutine on the current number — the number of the button.

When the buttons are pressed, the button's number is meant to be output. For example, if button '3' was pressed, '3' would be outputted to the console. However, when any of the buttons are output, '5' is output.

I know why this is — it's because the variable 'num' changes throughout the program and it ends up as 5, therefore '5' is output when I press any button. When the 'num' changes, it changes in all the Buttons' commands therefore they all do the same thing.

My question is, how can I avoid the command changing when the 'num' variable changes?

CodePudding user response:

from tkinter import Button

def action(n):
    print(n)
    
for num in range(1, 6):
    Button(text=str(num), command=lambda n=num: action(n)).pack()

Define the default argument n=num with the lambda function, so num gets captured and n with the value of num is used. In your code you pass n=num to the lambda function, but you are not defining it, so n is undefined.

  • Related