Question

Premise: I am trying to make a bunch of buttons in Tkinter and put them in a grid layout one after the other. I don't want to hard code each grid value that way I can add more buttons later with ease.

My first thought was to:

Button(root, text = "example", command = self.example_action).grid(row = count++)

But this did not work, I did some searching and found that python does not have a pre or post increment operator (Behaviour of increment and decrement operators in Python). So my next thought was to:

Button(root, text = "example", command = self.example_action).grid(row = count = count + 1)

This gives: SyntaxError: invalid syntax

So other than splitting my code onto two lines (use the variable then update it on the next line) is there a good way to do this all on one line to make my code more beautiful?

Was it helpful?

Solution

I suppose you could use a generator. Initialize count like:

count = itertools.count()

then you can do the following as much as you like

Python 2.x:

Button(root, text = "example", command = self.example_action).grid(row = count.next())

Python 3.x:

Button(root, text = "example", command = self.example_action).grid(row = next(count))

But I probably wouldn't

OTHER TIPS

I suppose count is an integer. Since it is immutable, you would not be able to change its value. In other words, whatever you do to 'row' inside the function, after the function returns, the value of 'row' will not change.

>>> row = 2
>>> def plus(i):
...     i = i + 1
...
>>> plus(row)
>>> row
2
>>>

So I suggest you store 'row' as an instance variable so that you can change its value by doing 'self.row += 1'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top