在for循环中生成时标识按钮

时间:2018-11-17 03:15:27

标签: python python-3.x button tkinter

我正在尝试使用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”。

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

谢谢!

1 个答案:

答案 0 :(得分:2)

def ConvertData(self): dataSets = [self.trainData, self.testData] for i, dataSet in enumerate(dataSets): convertedDataSet = ... do_something(dataSet) ... dataSets[i] = convertedDataSet 中为rowcol变量分配了每个值。在生成按钮的循环结束时,这些变量的值保留在范围内的最后一个值,例如“ 9:9”。

尝试替换行

range

使用

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的值分配给变量colrw,这两个变量对于每个按钮都保持不变。 for循环迭代。

查看此链接: Tkinter assign button command in loop with lambda