Home > Enterprise >  How to add a crosshair cursor into figure in tkinter?
How to add a crosshair cursor into figure in tkinter?

Time:04-11

I am currently working with Tkinter and have a matlabplot embedded in the window. I would like to add a crosshair to this figure. Unfortunately I do not succeed.

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.widgets import Cursor
import numpy as np
from tkinter import Tk, Frame
from PIL import Image
import requests


class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("Tool")

        # Add figure
        self.fig = plt.figure(figsize=(10, 6))
        self.ax = plt.gca()
        url = "https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png"
        img = Image.open(requests.get(url, stream=True).raw)
        self.data_matrix = np.asarray(img)

        # Add cursor
        cursor = Cursor(self.ax, useblit=True, color='red', linewidth=2)
        plt.imshow(self.data_matrix, cmap='gray')

        # Add graph
        canvas = FigureCanvasTkAgg(self.fig, master=master)
        canvas.draw()
        canvas.get_tk_widget().grid(row=1, column=0, sticky='S')

        # Add toolbar
        toolbarframe = Frame(master=master)
        toolbarframe.grid(row=2, column=0)
        toolbar = NavigationToolbar2Tk(canvas, toolbarframe)


def destroyer():
    root.quit()
    root.destroy()


root = Tk()
root.protocol("WM_DELETE_WINDOW", destroyer)
my_gui = MyFirstGUI(root)
root.mainloop()

How can i do that?

Thank you!

CodePudding user response:

I solved it on my own. I'm using the Blitted Cursor and added the class to my .py! Instead of self.ax.figure.canvas.draw(), I changed it to self.ax.figure.canvas.draw_idle().

To use the cursor, I've added:

self.cursor = Cursor(self.ax)
self.fig.canvas.mpl_connect('motion_notify_event', self.cursor.on_mouse_move)
  • Related