如何获取按钮的行和列信息并使用它来更改其在python中的设置

Min*_*ute 1 tkinter widget button python-3.x

我正在创建一个游戏,并试图在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()
Run Code Online (Sandbox Code Playgroud)

这是创建网格的主要部分,直到这一步为止:

    if btn(row,column) in pirate:
    btn.configure(text="P")
Run Code Online (Sandbox Code Playgroud)

所以我想知道是否有一种获取行和列并查看其是否在列表中的方法?

谢谢

Ste*_*ric 5

您可以调用.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()
Run Code Online (Sandbox Code Playgroud)

  • 您遇到的问题是因为您正在键入以在 NoneType 对象(无)上调用 `grid_info`。它在你的代码中:`btn = tkinter.Button(boardcanv, text="O").grid(row=rownum,column=colnum)`。不要在定义按钮的同一行调用 .grid(),首先声明它:`btn = tkinter.Button(boardcanv, text="O")` 然后将它放置在 `btn.grid(row= rownum,column=colnum)` (2认同)