I am creating a memory game and am running into a problem with the buttons. I create the buttons using a for loop and place them into an array, but I have no idea how to call a definition OnButtonClick for each one of them. Each button should have a random picture, chosen from eight options, with no more than two duplicates.
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()
How would I go about changing the picture when the buttons are pressed?
I didn't check if your code is working properly but if it works than you have to do something like this:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.