首页 > 解决方案 > 在 for 循环中生成时识别按钮

问题描述

我正在尝试使用 tkinter 在 python 上编写扫雷游戏。我首先使用二维列表创建了一个按钮网格,然后生成了按钮,一切正常。我唯一的问题是我不知道如何确定单击了我的网格中的哪个按钮。我的目标是能够点击一个按钮,通过它我知道我的网格 [row][col] 中的坐标。

这是我到目前为止的代码。

from tkinter import *
from functools import partial
from itertools import product

# Here, we are creating our class, Window, and inheriting from the Frame
# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
class Window(Frame):


    # Define settings upon initialization. Here you can specify
    def __init__(self, master=None):

        # parameters that you want to send through the Frame class. 
        Frame.__init__(self, master)   

        #reference to the master widget, which is the tk window                 
        self.master = master

        #with that, we want to then run init_window, which doesn't yet exist
        numRows = int(input("# of Rows: "))
        numCols = int(input("# of Cols: "))

        self.init_window(numRows, numCols)

    #Creation of init_window
    def init_window(self, rowNum, colNum):
        # print(x, y)
        # changing the title of our master widget      
        self.master.title("GUI")

        # allowing the widget to take the full space of the root window
        self.pack(fill=BOTH, expand=1)

        # creating a button instance
        #quitButton = Button(self, text="Exit",command=self.client_exit)

        # placing the button on my window
        #quitButton.place(x=0, y=0)
        but = []
        for row in range(0, rowNum):
            curRow = []
            for col in range(0, colNum):
                curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))
                curRow[col].grid(row=row,column=col)
            but.append(curRow)

        #but[1][1].config(state="disabled")
        #but[1][1]["text"] = "3"
        #but[1][1]["bg"] = "white"

    def open_button(self, r, c):
        print(r, " : ", c)

# root window created. Here, that would be the only window, but
# you can later have windows within windows.
root = Tk()

root.geometry("600x600")

#creation of an instance
app = Window(root)

#mainloop 
root.mainloop()

每当我单击网格时,它都会给我最后一个按钮......例如,每当我单击任何按钮时,9x9 网格总是给我“9:9”。

欢迎解决!我想要一种简单的方法来获取坐标而不更改太多代码(如果可能的话)。

谢谢!

标签: pythonpython-3.xbuttontkinter

解决方案


rowcol变量被分配到 s 中的每个值range。在生成按钮的循环结束时,这些变量的值保留在范围内的最后一个值,例如“9 : 9”。

换线试试

curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))

curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda rw=row, cl=col: self.open_button(rw, cl)))

这会将创建按钮时的row和的值分配给col变量rwcl,随着 for 循环的迭代,每个按钮的变量保持不变。

请参阅此链接: Tkinter 在循环中使用 lambda 分配按钮命令


推荐阅读