前提:我正在尝试用Tkinter制作一堆按钮,并将它们一个接一个地放在网格布局中。我不想硬编码每个网格值,这样以后我就可以轻松地添加更多的按钮。
我的第一个想法是:
Button(root, text = "example", command = self.example_action).grid(row = count++)但是这不起作用,我做了一些搜索,发现python没有前增量运算符或后增量运算符(Behaviour of increment and decrement operators in Python)。所以我的下一个想法是:
Button(root, text = "example", command = self.example_action).grid(row = count = count + 1)这会给出: SyntaxError:无效语法
因此,除了将我的代码拆分为两行(使用变量,然后在下一行更新它)之外,有没有一种好方法可以在一行中完成所有这些操作,使我的代码更美观?
发布于 2013-07-18 05:57:30
我想你可以用发电机。初始化计数如下:
count = itertools.count()然后,您可以随意执行以下操作
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))但我可能不会
发布于 2013-07-18 05:52:45
我认为count是一个整数。因为它是不可变的,所以你不能改变它的值。换句话说,无论你在函数中对'row‘做了什么,在函数返回之后,'row’的值都不会改变。
>>> row = 2
>>> def plus(i):
... i = i + 1
...
>>> plus(row)
>>> row
2
>>>因此,我建议您将'row‘存储为实例变量,以便您可以通过执行'self.row += 1’来更改它的值
https://stackoverflow.com/questions/17710849
复制相似问题