注意
前往結尾下載完整範例程式碼。
計時器#
使用一般計時器物件的簡單範例。這用於更新放置在圖形標題中的時間。
注意
此範例練習 Matplotlib 的互動功能,並且不會出現在靜態文件中。請在您的電腦上執行此程式碼以查看互動性。
您可以複製並貼上個別部分,或使用頁面底部的連結下載整個範例。

from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
def update_title(axes):
axes.set_title(datetime.now())
axes.figure.canvas.draw()
fig, ax = plt.subplots()
x = np.linspace(-3, 3)
ax.plot(x, x ** 2)
# Create a new timer object. Set the interval to 100 milliseconds
# (1000 is default) and tell the timer what function should be called.
timer = fig.canvas.new_timer(interval=100)
timer.add_callback(update_title, ax)
timer.start()
# Or could start the timer on first figure draw:
# def start_timer(event):
# timer.start()
# fig.canvas.mpl_disconnect(drawid)
# drawid = fig.canvas.mpl_connect('draw_event', start_timer)
plt.show()