【发布时间】:2018-11-17 03:15:27
【问题描述】:
我正在尝试使用 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”。
欢迎提出解决方案!我想要一种简单的方法来获取坐标而不更改太多代码(如果可能的话)。
谢谢!
【问题讨论】:
标签: python python-3.x button tkinter