在一行中定义相似但不相等的变量

时间:2017-01-23 14:42:38

标签: python loops variables tkinter iteration

作为我的问题的一个例子,我在屏幕上制作按钮。所有按钮都具有完全相同的命令,但它们将被放置在窗口中的不同坐标处(使用tkinter)。使用相同的方法定义变量,例如:

apple, banana, pear = "fruit"

我如何定义按钮,每个按钮具有相同的尺寸和命令,但是具有递增的坐标。 如果我要逐个定义这些按钮,它看起来就像这样...

Button1 = Button(root, text= "Button", height = 1, width = 1, command = command, x = 20, y = 50)
Button2 = Button(root, text= "Button", height = 1, width = 1, command = command, x = 40, y = 50)
Button3 = Button(root, text= "Button", height = 1, width = 1, command = command, x = 60, y = 50)

但有没有办法使用类似循环的东西来定义这些按钮? 感谢。

2 个答案:

答案 0 :(得分:1)

将列表推导与解包一起使用。 (顺便提一下,你的第一个例子是ValueError。)

Button1, Button2, Button3 = [Button(root, text="Button", height=1, width=1, command=command, x=x, y=y)
                               for x,y in [(20, 50), (40,50), (60,50)]]

答案 1 :(得分:0)

您可以遍历列表:

ent.maj_users:
    class: EntBundle\Service\MajUsers
    arguments:
      - '@doctrine.orm.dbsync_entity_manager'