How to retrieve the row and column information of a button and use this to alter its settings in python

牧云@^-^@ 提交于 2020-01-21 05:47:25

问题


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?

Thanks


回答1:


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()


来源:https://stackoverflow.com/questions/37731654/how-to-retrieve-the-row-and-column-information-of-a-button-and-use-this-to-alter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!