我正在尝试实现一个名为“五连胜”的游戏。
我创建了一个 15×15 的列表来放置按钮。 (我使用 range(16) 因为我还想要一行和一列来显示行号和列号)
我希望我的实现就像单击按钮时一样,它变成一个标签。
但我不知道用户点击了哪个按钮。
我怎样才能实现这一点?谢谢!
from tkinter import *
root=Tk()
root.wm_title("Five In a Row")
buttonlst=[ list(range(16)) for i in range(16)]
chess=Label(root,width=2,height=2,text='0')
def p(button):
gi=button.grid_info()
x=gi['row']
y=gi['column']
button.grid_forget()
chess.grid(row=x,column=y)
buttonlst[x][y]=chess
for i in range(16):
for j in range(16):
if i==0:
obj=Label(root,width=2,text=hex(j)[-1].upper())
elif j==0:
obj=Label(root,width=2,text=hex(i)[-1].upper())
else:
obj=Button(root,relief=FLAT,width=2,command=p(obj))
obj.grid(row=i,column=j)
buttonlst[i][j]=obj
root.mainloop()
有一个类似的问题如何确定Python TKinter中按钮网格中的哪个按钮被按下?。但我不太明白。
要将按钮实例传递给命令,您必须分两步完成。首先,创建按钮,然后在第二步中配置命令。另外,您必须使用 lambda 来创建所谓的closure.
例如:
obj=Button(root,relief=FLAT,width=2)
obj.configure(command=lambda button=obj: p(button))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)