[英]How to draw a Rectangle on Plot inside the FigureCanvasTkAgg using Tkinter?
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 中。 我想通过绘图上的鼠标事件添加一个矩形选择。 如何通过鼠标在图上添加动态矩形? 请帮我解决这个问题。
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 中绘制矩形
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.