我目前正在使用tkinter进行匹配/记忆游戏。
播放屏幕"只是一个按钮矩阵。我想要做的是给他们一个显示隐藏图像的命令并禁用按钮,如果下一个按下的按钮匹配,我需要它显然保持这样。
问题是我不知道如何做到这一点,因为我甚至不知道如何访问代码上的按钮。我的意思是,我创建了它们,但是现在我怎样才能输入每个特定的按钮来给它一个图像(因为游戏不能一直都是随机的BTW)然后给它命令留下或者不?
这可能是一个noob问题,但我只是进入了Matrices世界和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()
那么我需要知道如何访问矩阵的按钮?
谢谢!希望你能理解我的英语,因为它不是那里最好的。
再次感谢!
答案 0 :(得分:1)
您必须添加按钮到列表(或矩阵)
例如
self.all_buttons = []
# ...
boton = Button( ... )
self.all_buttons.append( boton )
然后您可以访问位置(x,y)
中的按钮self.all_buttons[y*longitud_j + x]
例如
self.all_buttons[y*longitud_j + x].grid( ... )
修改强>
BTW:您可以使用两个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()