首页 > 解决方案 > 单击矩形时如何为矩形着色?

问题描述

我正在使用 Python 进行编程;更准确地说,我正在使用该Matplotlib库创建两个两个矩形。我想要的是当我点击一个矩形时,矩形变成绿色。我不知道该怎么做。这是我的代码:

from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt

def plot_rectangle():
    fig = plt.figure(figsize=(9, 3))
    plt.axis('off')
    ax = plt.gca().axes
    rectangles = []
    rectangles.append(ax.add_patch(Rectangle((29, 2), width=.8, height=.8,
                       color='gray', alpha=.3)))
    rectangles.append(ax.add_patch(Rectangle((14, 4), width=.8, height=.8,
                       color='gray', alpha=.3)))
    plt.xlim(1, 32)
    plt.ylim(1, 13)
    for spine in plt.gca().spines.values():
        spine.set_visible(False)
    plt.tick_params(top=False, bottom=False, left=False, right=False)
    plt.show()
    def onclick(event):
        # when we click on a rectangle the rectangle becomes green
        pass
    fig.canvas.mpl_connect("button_press_event", onclick)


plot_rectangle()

标签: pythonmatplotlib

解决方案


推荐阅读