2017-01-23 56 views
0

作爲我的問題的示例,我在屏幕上生成按鈕。所有按鈕將具有完全相同的命令,但它們將被放置在窗口中的不同座標處(使用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) 

但是,有沒有辦法使用了一種類似於循環的東西來定義這些按鈕? 謝謝。

+0

'Button'類不支持'x'和'y'參數。你如何期望使用這些座標?他們是行/列值?像素值? –

+0

我只是用它作爲一個快速的例子來得到一般的想法 –

回答

0

您可以遍歷List:

buttons = [] 
for p in [(20,50),(40,50),(60,50)]: 
    buttons += [Button(root, text= "Button", height = 1, width = 1, command = command, x = p[0], y = p[1])] 
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)]]