9.7.3 左键响应

canvas的左键点击没有button方便,因为canvas是一个整体。点击然后显示数字这个功能需要更多工作:
1.获取鼠标点击时的坐标
2.从坐标计算出按钮是几行几列,这可以从上一节的显示所有数字那里把代码复制过来
import tkinter as tk
def generateMines():
  #代码省略,整一个模拟数据
  return [[0, 0, 0, 0, 0, 1, 1, 1, 0, 0], 
[0, 1, 1, 1, 0, 1, 9, 1, 0, 0], 
[1, 2, 9, 1, 1, 2, 2, 1, 0, 0], 
[9, 2, 1, 1, 1, 9, 2, 1, 0, 0], 
[1, 1, 0, 0, 1, 2, 9, 2, 1, 0], 
[1, 1, 1, 1, 1, 1, 2, 9, 1, 0], 
[9, 1, 1, 9, 1, 0, 2, 2, 2, 0], 
[2, 2, 1, 1, 1, 0, 1, 9, 1, 0], 
[9, 1, 0, 0, 0, 0, 1, 1, 1, 0], 
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]
#左键单击事件
def left_click(event):
  
    # 获取当前事件所在的画布对象
    canvas = event.widget
    # 将事件坐标转换为画布坐标,x和y是鼠标点击时的坐标
    x, y = canvas.canvasx(event.x), canvas.canvasy(event.y)
    print(x,y)
root = tk.Tk()
mines = generateMines()  # 生成地雷矩阵
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
# 创建一个10x10的按钮矩阵
for i in range(10):
    for j in range(10):
        x, y = j * 30, i * 30
        #创建方块,tag是方块的id,可以通过此id找到方块
        rec = canvas.create_rectangle(x, y, x + 30, y + 30, fill="#ccc", outline="gray",
                                      tags=("button_{}_{}".format(i, j),))
        
# 进入事件循环
root.mainloop()