python - 如何使用 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 中。我想通过鼠标事件在绘图上添加一个矩形选择。如何在图上用鼠标添加动态矩形?请帮我解决这个问题。
解决方案
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 中绘制矩形
推荐阅读
- jenkins - 在扩展选择参数中访问环境变量
- c# - 使用 .NET `Confluent.Kafka` `subscribe`/`assign` 到 Kafka 主题的正确方法是什么?
- swift - NotificationCenter:多次切换键盘将 y 位置设置为奇怪的值
- terraform - 如何将 .env 文件中的环境变量读入 terraform 脚本?
- flutter - 无限滚动颤振
- razor - 2sxc 10.25 上的 Mobius Form 3 错误?
- javascript - jQuery获取上一个元素未按预期工作
- php - 在 LARAVEL 6 中发布路线
- python - 从标准输入读取时,没有换行符的 print() 不起作用
- laravel - 创建字段后,我无法将值保存在数据库中