1

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?

user202729
  • 3,358
  • 3
  • 25
  • 36
jnedrud
  • 47
  • 6
  • 1
    I wouldn't consider one line code to be more beautiful in many cases, especially your case. My personal opinion is that better readability results in more "beautiful" code (together with PEP-8 conventions, maybe) – woozyking Jul 17 '13 at 21:49
  • Python wants you to do it in two lines – Michael Butscher Jul 17 '13 at 21:52

2 Answers2

1

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

jrobichaud
  • 1,272
  • 1
  • 11
  • 23
cmd
  • 5,754
  • 16
  • 30
  • Thanks, that is what I was looking for. But as you and other commenters have pointed out, doing something like this and putting it all on one line may not be worth it. – jnedrud Jul 17 '13 at 22:02
0

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'

Conan Li
  • 474
  • 2
  • 6
  • I believe row is a named argument of the function grid(). I am trying to increment counter, which is a variable, then pass by value the result of the increment to the function – jnedrud Jul 17 '13 at 21:57
  • sorry, i guess i meant 'count' instead of 'row'. If you want to change 'count', you will need to store it as self.count – Conan Li Jul 17 '13 at 21:59