How can I identify buttons, created in a loop?

后端 未结 4 1053
借酒劲吻你
借酒劲吻你 2020-12-06 15:29

I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list of 10x10. Then I created each but

4条回答
  •  抹茶落季
    2020-12-06 16:08

    If you just want to destroy the Button widget, the simple way is to add the callback after you create the button. Eg,

    import Tkinter as tk
    
    grid_size = 10
    
    root = tk.Tk()
    blank = " " * 3
    for y in range(grid_size):
        for x in range(grid_size):
            b = tk.Button(root, text=blank)
            b.config(command=b.destroy)
            b.grid(column=x, row=y)
    
    root.mainloop()
    

    However, if you need to do extra processing in your callback, like updating your grid of buttons, it's convenient to store the Button's grid indices as an attribute of the Button object.

    from __future__ import print_function
    import Tkinter as tk
    
    class ButtonDemo(object):
        def __init__(self, grid_size):
            self.grid_size = grid_size
            self.root = tk.Tk()
            self.grid = self.button_grid()
            self.root.mainloop()
    
        def button_grid(self):
            grid = []
            blank = " " * 3
            for y in range(self.grid_size):
                row = []
                for x in range(self.grid_size):
                    b = tk.Button(self.root, text=blank)
                    b.config(command=lambda widget=b: self.delete_button(widget))
                    b.grid(column=x, row=y)
                    #Store row and column indices as a Button attribute
                    b.position = (y, x)
                    row.append(b)
                grid.append(row)
            return grid
    
        def delete_button(self, widget):
            y, x = widget.position
            print("Destroying", (y, x))
            widget.destroy()
            #Mark this button as invalid 
            self.grid[y][x] = None
    
    ButtonDemo(grid_size=10)
    

    Both of these scripts are compatible with Python 3, just change the import line to

    import tkinter as tk
    

提交回复
热议问题