Python 根据x,y坐标隐藏小部件

Python 根据x,y坐标隐藏小部件,python,button,minesweeper,Python,Button,Minesweeper,说到编程,我是个新手,在学校的编程练习中,我正在用python用TKinter作为GUI制作一个扫雷游戏。 除了我的泛光填充算法,这个游戏可以清除任何相邻的空格。 我制作了一个图板,根据用户选择的地雷的高度、宽度和数量打印了一个先前创建的列表,带有标签,并将这些标签隐藏在按钮后面 我可以绑定事件以在单击时隐藏这些按钮,但我还希望能够在泛光填充算法的帮助下隐藏附近的按钮。我觉得我需要的只是一行代码,它将根据x和y坐标隐藏按钮,而不仅仅是单击的按钮。 我想你已经想到了 def initGame(fi

说到编程,我是个新手,在学校的编程练习中,我正在用python用TKinter作为GUI制作一个扫雷游戏。 除了我的泛光填充算法,这个游戏可以清除任何相邻的空格。 我制作了一个图板,根据用户选择的地雷的高度、宽度和数量打印了一个先前创建的列表,带有标签,并将这些标签隐藏在按钮后面

我可以绑定事件以在单击时隐藏这些按钮,但我还希望能够在泛光填充算法的帮助下隐藏附近的按钮。我觉得我需要的只是一行代码,它将根据x和y坐标隐藏按钮,而不仅仅是单击的按钮。 我想你已经想到了

def initGame(field, height, width, mn):     
    play = tk.Toplevel()
    play.grid()
    title = ttk.Label(play, text= "MineSweeper")
    title.grid(row=0)
    playfield = tk.LabelFrame(play, text = None)
    playfield.grid(row = 1, rowspan = height+2, columnspan = width+2)       
    mine = tk.PhotoImage(file='mine.gif')
    for i in range(1, height+1):
        for j in range(1, width+1):             
            if  field[i][j] == '9':
                val = tk.Label(playfield, image = mine)
                val.image=mine
            else:
                val = tk.Label(playfield, text= "%s" %(field[i][j]))
            val.grid(row=i-1, column=j-1)
    blist = []
    for i in range(1, height+1):
        for j in range(1, width+1):
            btn = tk.Button(playfield, text = '   ')
            blist.append(btn)

            def handler(event, i=i, j=j):
                return floodfill(event, field, blist, j, i)
            btn.bind('<ButtonRelease-1>', handler)
            btn.bind('<Button-3>', iconToggle)
            btn.grid(row=i-1, column=j-1)

def floodfill(event, field, blist, x, y):
    edge = []
    edge.append((y,x))
    while len(edge) > 0:
        (y,x) = edge.pop()
        if field[y][x] != '9':
            #####################
        else:
            continue
        for i in [-1, 1]:
            for j in [-1, 1]:
                if y + i >= 1 and y + i < len(field)-1:       
                    edge.append((y + i, x))
                if x + j >= 1 and x + j < len(field[0])-1:
                    edge.append((y, x + j))
我相信,要让这个系统正常工作,我所需要的只是一条长长的线,比如button.positionx,y。 我试图将按钮保存在blist中,也许我可以在x和y坐标的帮助下得到需要隐藏的正确按钮


当然,如果你对如何解决这个问题有更好的想法,我很乐意听听。

将按钮保存在二维数组中,因此blist[x,y]表示位于x,y位置的按钮。当你知道x,y的位置时,按下正确的按钮应该是笔直的

编辑:

首先创建二维阵列

blist = []
for i in range(1, height+1):
    tmpList = []
    for j in range(1, width+1):
        btn = tk.Button(playfield, text = '   ')
        tmpList.append(btn)

        def handler(event, i=i, j=j):
            return floodfill(event, field, blist, j, i)
        btn.bind('<ButtonRelease-1>', handler)
        btn.bind('<Button-3>', iconToggle)
        btn.grid(row=i-1, column=j-1)

    blist.append(tmpList)

现在你可能需要在这里切换x和y-1因为您已经开始索引字段坐标中的1,我想。

您是否可以提供一个简短的示例,说明如何将坐标添加到列表中,然后隐藏按钮?它像blist[x,y]一样吗?你忘了吗?这在理论上应该是可行的,这个解决方案对我来说也非常优雅。如果y+i>=1和y+i if field[y][x] != '9': Button_To_Hide = blist[x-1][y-1] Button_To_Hide.grid_forget()