Để nhúng hoạt ảnh matplotlib vào khung tkinter, chúng ta có thể thực hiện các bước sau
Các bước
-
Đặt kích thước hình và điều chỉnh phần đệm giữa và xung quanh các ô con.
-
Tạo tiện ích con Toplevel của Tk phần lớn đại diện cho cửa sổ chính của ứng dụng
-
Đặt tiêu đề của tiện ích con này.
-
Thêm một trục vào hình hiện tại và biến nó thành các trục hiện tại.
-
Tạo một hình mới hoặc kích hoạt một hình hiện có.
-
Thêm 'rìu' vào hình như một phần của sự sắp xếp lô phụ.
-
Tạo một biểu đồ dòng giả với linewidth =2 .
-
Tạo khung vẽ cho hình vẽ.
-
Tạo canvas hình để vận hành.
-
Tạo cách nhấn phím sự kiện để thoát khỏi mùa đông tkinter.
-
Tạo hoạt ảnh bằng cách gọi liên tục một hàm * hoạt ảnh * .
-
Để hiển thị hình này, hãy sử dụng Show () phương pháp.
Ví dụ
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")
plt.axes(xlim=(0, 2), ylim=(-2, 2))
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() Đầu ra
Nó sẽ tạo ra kết quả sau -