2017-02-13 96 views
0

我正在创建一个记忆游戏,并遇到按钮的问题。我使用for循环创建按钮并将它们放入数组中,但我不知道如何为它们中的每一个调用定义OnButtonClick。每个按钮应该有一个随机图片,从八个选项中选择,不超过两个副本。与Tkinter的Python记忆游戏 - 定义和按钮的问题

from Tkinter import * 
import Tkinter 
import random 

root = Tkinter.Tk() 

poop=PhotoImage(file="poop.gif") 
apple=PhotoImage(file="apple.gif") 
earth=PhotoImage(file="earth.gif") 
fish=PhotoImage(file="fish.gif") 
frowny=PhotoImage(file="frowny.gif") 
heart=PhotoImage(file="heart.gif") 
smiley=PhotoImage(file="images.gif") 
water=PhotoImage(file="water.gif") 
back=PhotoImage(file="card back.gif") 

images = [poop,apple,earth,fish,frowny,heart,smiley,water] 
row = 1 
column = 0 
buttonList=[] 

def OnButtonClick(): 
    self.Button.config(image=random.choice(images)) 

for i in range(16): 
    buttonList.append(Button(root, image=back,  width=150,height=250,command=OnButtonClick())) 
buttonList[i].grid(row = row,column = column) 


column += 1 
if column == 4: 
    column = 0 
    row += 1 





root.mainloop() 

如何在按下按钮时更改图片?

+0

你生成它们以同样的方式,你需要去通过接入数组中的每个(特定元素)元素都可以更改图像。 – Afflicted

回答

0

我没有检查,如果你的代码工作正常,但如果它比你必须做这样的事情:

def OnButtonClick(number): 
    buttonList[number].config(image=random.choice(images)) 

for i in range(16): 
    buttonList.append(Button(root, image=back,width=150,height=250,command=lambda e=i: OnButtonClick(e))) 
    buttonList[i].grid(row=row, column=column)