带Tkinter的Python内存游戏的定义和按钮问题

2024-09-30 14:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

当按钮按下时,我该如何更改图片?在


Tags: importappletkintercolumnrootgif按钮file
1条回答
网友
1楼 · 发布于 2024-09-30 14:38:19

我没有检查您的代码是否正常工作,但如果它能正常工作,您必须执行以下操作:

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)

相关问题 更多 >