繁体   English   中英

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

[英]hiding a widget according to x, y coordinates

在编程方面,我是一个新手,在学校的编程实践中,我正在使用TKinter作为GUI使用python开发扫雷游戏。 除我的“填充”算法外,该游戏可以清除任何相邻的空白。 我已经按照用户选择的选项(高度,宽度和地雷数量)制作了木板,打印了先前创建的列表,并带有标签,并将这些标签隐藏在按钮后面。

我可以绑定事件以在单击时隐藏这些按钮,但是我还希望能够借助Floodfill算法在附近隐藏按钮。 我觉得我只需要一行代码即可根据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.position(x,y)。我试图将按钮保存在blist中,也许我可以获得在x和y坐标的帮助下需要隐藏的正确按钮?

当然,如果您有更好的解决方案,我很想听听。

将按钮保存在2D数组中,因此blist [x,y]表示按钮在x,y位置。 当您知道x,y位置应该是直截了当时,请获得正确的按钮。

编辑:

首先创建2D数组。

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)

然后使用它来获取泛洪功能中的按钮对象:

 if field[y][x] != '9':
        Button_To_Hide = blist[x-1][y-1] 
        Button_To_Hide.grid_forget()

现在您可能需要在此处切换x和y。 -1,因为您已经开始在字段的坐标中用1索引(我认为)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM