Để nhúng animation Matplotlib vào khung (frame) tkinter, bạn có thể thực hiện theo các bước sau:
Các bước thực hiện
- Thiết lập kích thước hình vẽ và điều chỉnh khoảng cách giữa các subplot.
- Tạo widget Toplevel của Tk (cửa sổ chính ứng dụng).
- Đặt tiêu đề cho widget.
- Thêm axes vào figure hiện tại và đặt làm axes hiện tại.
- Tạo figure mới hoặc kích hoạt figure hiện có.
- Thêm ax vào figure như một phần của bố cục subplot.
- Tạo đường vẽ giả (dummy line) với linewidth=2.
- Tạo canvas để figure render vào.
- Tạo figure canvas để thao tác.
- Tạo sự kiện keypress để thoát cửa sổ tkinter.
- Tạo animation bằng cách gọi lặp lại hàm animate.
- Sử dụng tkinter.mainloop() để chạy vòng lặp sự kiện.
Ví dụ minh họa
import tkinter
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from matplotlib import pyplot as plt, animation
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
fig = plt.Figure(dpi=100)
ax = fig.add_subplot(xlim=(0, 2), ylim=(-1, 1))
line, = ax.plot([], [], lw=2)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.update()
canvas.mpl_connect("key_press_event", lambda event: print(f"you pressed {event.key}"))
canvas.mpl_connect("key_press_event", key_press_handler)
button = tkinter.Button(master=root, text="Quit", command=root.quit)
button.pack(side=tkinter.BOTTOM)
toolbar.pack(side=tkinter.BOTTOM, fill=tkinter.X)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
tkinter.mainloop()
Kết quả đầu ra
Cửa sổ tkinter hiển thị animation sóng sin di chuyển, có toolbar điều hướng và nút Quit.