我正在创建一个游戏并尝试在python和tkinter中创建它。我已经在基于单词的python中完成了它并且想要使它成为图形化的。 我创建了一个用作网格的按钮网格,这些按钮当前在其上有字母“O”以显示空白区域。但是,我想要的是按钮来显示海盗所在的文本,然后最终显示玩家和箱子。由于位置是随机选择的,因此无法对文本进行硬编码。
while len(treasure)<chestLimit:
currentpos=[0,0]
T=[random.randrange(boardSize),random.randrange(boardSize)]
if T not in treasure or currentpos:
treasure.append(T)
while len(pirate)<pirateLimit:
P=[random.randrange(boardSize),random.randrange(boardSize)]
if P not in pirate or treasure or currentpos:
pirate.append(P)
boardselectcanv.destroy()
boardcanv=tkinter.Canvas(window, bg="lemonchiffon", highlightcolor="lemonchiffon", highlightbackground="lemonchiffon")
boardcreateloop=0
colnum=0
while colnum != boardSize:
rownum=0
while rownum != boardSize:
btn = tkinter.Button(boardcanv, text="O").grid(row=rownum,column=colnum)
boardcreateloop+=1
rownum+=1
colnum+=1
if btn(row,column) in pirate:
btn.configure(text="P")
boardcanv.pack()
这是创建网格的主要部分,直到此为止:
if btn(row,column) in pirate:
btn.configure(text="P")
所以我想知道是否有办法获取行和列,看看它是否在列表中?
由于
答案 0 :(得分:3)
您可以在按钮小部件上调用.grid_info()
以获取其网格信息。
from tkinter import *
root = Tk()
def showGrid():
row = btn.grid_info()['row'] # Row of the button
column = btn.grid_info()['column'] # grid_info will return dictionary with all grid elements (row, column, ipadx, ipday, sticky, rowspan and columnspan)
print("Grid position of 'btn': {} {}".format(row, column))
btn = Button(root, text = 'Click me!', command = showGrid)
btn.grid(row = 0, column = 0)
root.mainloop()