如何检索按钮的行和列信息并使用它来更改其在 python 中的设置 [英] How to retrieve the row and column information of a button and use this to alter its settings in python
问题描述
我正在创建一个游戏并尝试在 python 和 tkinter 中制作它.我已经在基于单词的 python 中完成了它,并希望使其图形化.我创建了一个用作网格的按钮网格,这些按钮当前带有字母O"以显示空白区域.但是,我想要的是显示海盗在哪里的文本,然后是玩家和箱子的按钮.由于位置是随机选择的,因此无法对文本进行硬编码.
I am creating a game and trying to make it in python and tkinter. I have already completed it in word-based python and want to make it graphical. I have created a grid of buttons to be used as a grid and these buttons currently have the letter "O" on them to show an empty space. However, what I would like is the button to show text of where a pirate is and then eventually the player and chests. The text cannot be hard coded as the positions are randomly selected.
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()
这是创建网格的主要部分,一直到此为止:
This is the main section of creating the grid and works up until this point:
if btn(row,column) in pirate:
btn.configure(text="P")
所以我想知道是否有办法获取行和列并查看它是否在列表中?
So I was wondering if there was a way to get the row and column and see if it is in the list?
谢谢
推荐答案
您可以在按钮小部件上调用 .grid_info()
以获取其网格信息.
You can call .grid_info()
on a button widget to get its grid information.
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()
这篇关于如何检索按钮的行和列信息并使用它来更改其在 python 中的设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!