首页 > 解决方案 > 如何使用 Tkinter 在 FigureCanvasTkAgg 内的 Plot 上绘制一个矩形?

问题描述

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.patches as patches
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.pyplot as plt
import tkinter
window = Tk()

# Create figure and axes
fig, ax = plt.subplots()
fig.patch.set_facecolor('black')
fig.set_size_inches(8, 4.14)
ax.tick_params(axis='x', colors='white')
ax.tick_params(axis='y', colors='white')
plt.tight_layout()
# Display the image
ax.imshow(image_array, aspect='auto')  

# plt.show()

canvas =FigureCanvasTkAgg(fig, master=window)
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.BOTTOM)

toolbar = NavigationToolbar2Tk(canvas, HEImageFrameElem)
toolbar.update()

canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.LEFT, expand=1)
window.mainloop()

我可以使用上面的代码将绘图集成到我的 Tkinter UI 中。我想通过鼠标事件在绘图上添加一个矩形选择。如何在图上用鼠标添加动态矩形?请帮我解决这个问题。

标签: pythonpython-3.xtkinter-canvas

解决方案


  def line_select_callback(eclick, erelease):
     global x1
     global x2
     global y1
     global y2
     print(" The button you used were: %s %s" % (eclick.button, erelease.button))
           "eclick and erelease are the press and release events"
    x1, y1 = eclick.xdata, eclick.ydata
    x2, y2 = erelease.xdata, erelease.ydata

     # reading rectangle coordinate values to class variables
     x1 = int(x1)
     y1 = int(y1)
     x2 = int(x2)
     y2 = int(y2)

     toggle_selector.RS = RectangleSelector(
                axF,
                line_select_callback,
                drawtype="box",
                useblit=False,
                button=[1, 3],
                minspanx=0,
                minspany=0,
                spancoords="pixels",
                interactive=True,
                rectprops=dict(edgecolor="white", fill=False),
            )
    
        x1 = 5
        y1 = 5
        x2 = 15
        y2 = 15
    
        toggle_selector.RS.to_draw.set_visible(True)
    
        toggle_selector.RS.extents = (x1, x2, y1, y2)

使用上述方法,我将能够在 MatplotLib 中绘制矩形


推荐阅读