0

I'm trying to build a tkinter GUI, and I'm having a Python programming logic issue. My problem is the following: I'm creating a bunch of objects in the following way:

class Aplication:
    def createObjects(self):
        objects = []
        for i in range(10):
            obj = Object(command = lambda: self.myFunction(i))
            objects.append(obj)

    def myFunction(self, i):
        print(i)

And when executing each object's command I expected the result:

0
1
2
3
4
5
6
7
8
9

But instead I'm getting:

9
9
9
9
9
9
9
9
9
9

I simplified my code so that anyone who knows Python logic can help me. Appreciate any help in advance.

0

1 Answer 1

2

This slightly modified version works as you expect.

It is essentially the variable scope problem. In your implementation, the function looks for i in the runtime, when i has already been updated to 9. If you want to keep the "current" value of i, you need to define a function with the current i like below.

class Object:
    def __init__(self, command):
        self.command = command
        
class Application:
    def createObjects(self):
        objects = []
        for i in range(10):
            obj = Object(command = self.myFunction(i))
            objects.append(obj)
        return objects
    
    def myFunction(self, i):
        return lambda: print(i)

a = Application()
os = a.createObjects()
for o in os:
    o.command()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.