上面的代码绘制了一个基本网格。我想做以下事情。
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
n = 2**3
plt.axes(xlim = (0, n), ylim = (0, n))
plt.axis('off')
for line in range(n):
for col in range(n):
rect = mpatches.Rectangle(
(line, col), 1, 1,
facecolor = "white",
edgecolor = "black"
)
plt.gca().add_patch(rect)
plt.show()
答案 0 :(得分:2)
这是一个解决方案,其中矩形的绘制尚未分解。确实matplotlib
为事件提供了一个非常容易使用的界面。
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
n = 2**3
def drawInitial():
plt.axes(xlim = (0, n), ylim = (0, n))
plt.axis('off')
for line in range(n):
for col in range(n):
rect = mpatches.Rectangle(
(col, line), 1, 1,
facecolor = "white",
edgecolor = "black"
)
plt.gca().add_patch(rect)
def onclick(event):
col = int(event.xdata)
line = int(event.ydata)
rect = mpatches.Rectangle(
(col, line), 1, 1,
facecolor = "black",
edgecolor = "black"
)
plt.gca().add_patch(rect)
plt.draw()
def onkey(event):
if event.key == " ":
drawInitial()
plt.draw()
fig = plt.figure()
fig.canvas.mpl_connect('button_press_event', onclick)
fig.canvas.mpl_connect('key_press_event', onkey)
drawInitial()
plt.show()