簡體   English   中英

Tkinter的Python記憶游戲-定義和按鈕問題

[英]Python Memory Game with Tkinter - Trouble with definitions and buttons

我正在創建一個記憶游戲,但按鈕遇到了問題。 我使用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()

按下按鈕后如何更改圖片?

我沒有檢查您的代碼是否正常運行,但是如果可以正常運行,則必須執行以下操作:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM