Home Python 3: How do I place an incrementing literal in a loop?
Reply: 1

Python 3: How do I place an incrementing literal in a loop?

rgblaine Published in 2017-11-12 15:44:17Z

I want to set up a list of buttons inside a loop, with each button's command calling a function with a different value.

for rank in range(21):
    self._rankButton.append(Button(self, text = "Rank " + str(rank),
        command = self._setDice(rank))

self._rankButton[0] should call self._setDice(0)
self._rankButton[1] should call self._setDice(1)
self._rankButton[20] should call self._setDice(20)

the only way I get this to work is by configuring the buttons individually outside the loop

VPfB Reply to 2017-11-12 16:01:47Z

Don't know what the Button is, but it looks like it expects a function to be called. So you must create that function:

...., command=lambda r=rank: self._setDice(r)

This should work, unfortunately it is not well readable. First lambda means makefunction. Second, there is a issue with late binding, that's why we must introduce r, because rank will have another value at the time this will be called.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.329527 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO