1

The code above draws a basic grid. I would like to do the following things.

  1. Know where the user clicks on the draw so as to change the face color of a rectangle. The problem is to know that the user has clicked and then to have the coordinates of the click. Is it possible ?
  2. I would like also to interact with key events. For example, if the space key is activated, I would like to go back to the initial draw. The problem is to know that a key has been pressed, and to have the ascii code of this key. Is it possible ?

MY STARTING CODE

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()
2
  • 1
    Yes, it is possible and not very difficult. Start reading here: matplotlib.org/users/event_handling.html Commented Nov 12, 2013 at 16:38
  • Could you post what you did as an answer to your own question? Commented Nov 12, 2013 at 16:50

1 Answer 1

2

Here is a solution where the draw of the rectangle has not been factorized. Indeed matplotlib gives a very easy to use interface for events.

#!/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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.