tkinter/按钮与矩阵绑定的简单匹配博弈

2024-09-28 01:28:32 发布

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

我正在用tkinter制作一个匹配/记忆游戏。在

“播放屏幕”只是一个按钮矩阵。我想做的是给他们一个命令,显示隐藏的图像,并禁用按钮,如果下一个按下的按钮是匹配的,我需要它显然保持这样。在

问题是我不知道该怎么做,因为我甚至不知道如何访问代码上的按钮。我的意思是,我创造了它们,但是现在我怎么能输入每个特定的按钮给它一个图像(顺便说一句,因为游戏不可能一直都是一样的),然后给它留下或不留下的命令呢?在

这可能是一个很难回答的问题,但我刚进入矩阵世界。在

以下是我到目前为止所做的。。。在

from tkinter import *


def VentanaPlay():
    matriz = [[0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0]]

    ventana = Tk()
    ventana.title('Ejemplo')

    longitud_i = len(matriz)
    longitud_j = len(matriz[0])

    def creaMatriz(i = 0, j = 0):
        if i == longitud_i and j == longitud_j:
            print('Listo')
        elif j < longitud_j:
            boton = Button(ventana, width = 10, height = 5)
            boton.grid(row = i, column = j)
            return creaMatriz(i, j + 1)
        else:
            return creaMatriz(i + 1, 0)

    creaMatriz()

    ventana.mainloop()

VentanaPlay()

所以我需要知道如何访问矩阵的按钮?在

谢谢!希望你能理解我的英语,因为它不是最好的。在

再次感谢!在


Tags: 图像命令游戏lenreturntkinterdef矩阵
1条回答
网友
1楼 · 发布于 2024-09-28 01:28:32

你必须将按钮添加到列表(或矩阵)

例如

self.all_buttons = []

# ...

boton = Button( ... )
self.all_buttons.append( boton )

然后你可以在位置(x,y)访问按钮

^{pr2}$

例如

self.all_buttons[y*longitud_j + x].grid( ... )

编辑:

顺便说一句:您可以使用两个for循环来代替递归来创建按钮


编辑:

完整示例(我更喜欢对象编程,所以我使用class):

单击任意按钮可将颜色更改为红色,再次单击可更改为绿色。在

from tkinter import *

class VentanaPlay():

    def __init__(self):

        self.matriz = [
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0]
        ]

        self.all_buttons = []

        self.ventana = Tk()
        self.ventana.title('Ejemplo')

        #self.long_x = len(self.matriz)

        #self.long_y = len(self.matriz[0])

        self.creaMatriz()

    def run(self):
        self.ventana.mainloop()


    def creaMatriz(self):
        for y, row in enumerate(self.matriz):
            buttons_row = []
            for x, element in enumerate(row):
                boton = Button(self.ventana, width=10, height=5, command=lambda a=x,b=y: self.onButtonPressed(a,b))
                boton.grid(row=y, column=x)
                buttons_row.append( boton )
            self.all_buttons.append( buttons_row )

    def onButtonPressed(self, x, y):
        print( "pressed: x=%s y=%s" % (x, y) )
        if self.all_buttons[y][x]['bg'] == 'red':
            self.all_buttons[y][x]['bg'] = 'green'
        else:
            self.all_buttons[y][x]['bg'] = 'red'

VentanaPlay().run()

相关问题 更多 >

    热门问题