Matplotlib 简明教程
Matplotlib - Close Event
在编程和软件设计中, event 指的是软件识别的动作或事件。这些事件可以由系统、用户输入或其他来源触发,软件对此予以处理。
In the context of programming and software design, an event refers to an action or incident that is identified by the software. These events can be initiated by the system, user inputs, or other sources and are subject to handling by the software.
具体来说, close event 是当在软件界面中关闭图形时触发的一个事件。该事件意味着与图形关联的图形表示或窗口的终止或关闭,并且提醒软件相应地做出响应。
Specifically, a close event is an occurrence triggered when a figure is closed within the software interface. This event means the termination or closure of the graphical representation or window associated with the figure and reminds the software to respond accordingly.
Close Events in Matplotlib
Matplotlib 提供了一组处理事件的工具,其中包括处理关闭事件的功能。Matplotlib 中的 close event 发生在图形窗口关闭时,从而触发 Python 脚本中的特定操作。通过连接到 close_event,你可以执行自定义代码以响应关闭图形。
Matplotlib provides a set of tools to handle events, among them is the ability to handle close events. A close event in Matplotlib occurs when a figure window is closed, triggering specific actions within your Python script. By connecting to the close_event you can execute custom code in response to a figure being closed.
在本教程中,我们将探讨如何在 Matplotlib 中使用关闭事件来改善交互式图表。
In this tutorial, we will explore how to use close events in Matplotlib to enhance interactive plots.
Example
以下是一个简单的示例,它在用户关闭图形时显示一条消息。
Here is a simple example that displays a message when the user closes the figure.
import matplotlib.pyplot as plt
def on_close(event):
print('The Figure is Closed!')
fig, ax = plt.subplots(figsize=(7, 4))
ax.annotate('X', xy=(1, 1), xytext=(0.9, 0.65), fontsize=20,
arrowprops=dict(facecolor='red'),
horizontalalignment='left',
verticalalignment='bottom')
fig.canvas.mpl_connect('close_event', on_close)
ax.text(0.15, 0.5, 'Close This Figure!', dict(size=30))
plt.show()
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −

关闭上述输出图形后,以下消息将在控制台中显示 -
After closing the above output figure, the following message is displayed in the console −
The Figure is Closed!
Detecting Closed Axes
在处理图形中的多个轴时,你需要确定是否关闭了特定的轴,你可以使用 Matplotlib 中的关闭事件操作。
When dealing with multiple axes in a figure, you need to determine if a specific axis has been closed you can use the close event action in Matlotlib.
Example
以下示例演示了如何使用 Matplotlib 中的关闭事件来确定是否关闭了特定的轴。
Here is an example that demonstrates how to determine if a specific axis has been closed or not, using the close event in Matplotlib.
import matplotlib.pyplot as plt
# Function to handle the event
def on_close(event):
event.canvas.figure.axes[0].has_been_closed = True
print('The Figure is Closed!')
# Create the figure
fig, ax = plt.subplots(figsize=(7, 4))
ax.set_title('Detecting Closed Axes')
ax.has_been_closed = False
ax.plot(range(10))
# connect the event with the callable function
fig.canvas.mpl_connect('close_event', on_close)
plt.show()
print('Check the attribute has_been_closed:', ax.has_been_closed)
在执行上述程序后,你将获得以下输出 -
On executing the above program you will get the following output −

关闭上述输出图形后,以下消息将在控制台中显示 -
After closing the above output figure, the following message is displayed in the console −
The Figure is Closed!
Check the attribute has_been_closed: True
Continuing Code After Closing
在某些情况下,即使在图形关闭后,你的代码可能需要继续运行( close event triggered )。这对于后台进程或动画特别有用。
In some cases, it may be necessary for your code to continue running even after the figure is closed (close event triggered). This is particularly useful for background processes or animations.
Example
以下示例演示了在图形关闭后如何继续执行代码。
The following example demonstrates how to continue code execution after the figure is closed.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import time
close_flag = 0
def handle_close(evt):
global close_flag
close_flag = 1
print('The Figure is Closed!')
# Activate interactive mode
plt.ion()
fig, ax = plt.subplots()
# listen to close event
fig.canvas.mpl_connect('close_event', handle_close)
# Generating x values
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
# Plotting the initial sine curve
line, = ax.plot(x, y)
ax.legend([r'$\sin(x)$'])
# Function to update the plot for each frame of the animation
def update(frame):
line.set_ydata(np.sin(x + frame / 50))
return line
t = 0
delta_t = 0.1
while close_flag == 0:
if abs(t - round(t)) < 1e-5:
print(round(t))
x = x + delta_t
y = y - delta_t
# Creating a FuncAnimation object
ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30)
# draw the figure
fig.canvas.draw()
fig.canvas.flush_events()
# wait a little bit of time
time.sleep(delta_t)
t += delta_t
if close_flag == 1:
break
print('ok')
在执行上述程序后,你将获得以下输出 -
On executing the above program you will get the following output −

关闭上述输出图形后,以下消息将在控制台中显示 -
After closing the above output figure, the following message is displayed in the console −
0
1
2
3
4
5
The Figure is Closed!
ok
观看下方的视频,观察此处关闭事件功能如何工作。
Watch the video below to observe how the close event feature works here.
