[Python][Voice]Integrate a plot of matplotlib into tkinter GUI/整合matplotlib的繪圖到 tkinter圖形視窗中
This example shows how to integrate a plot or figure on matplotlib into the graphic user interface of tkinter.
Import tkinter
Import matplotlib
Import FigureCanvasTkAgg
Import Figure
Build a window named “win”.
Window format 1: title()
Window format 2: geometry() determine size and initial position(x,y)
Window format 3: maxsize() set max size of a window
Build a figure with figsize = (Width: inch, Length: inch) and dpi = pixel per inch
Add the subplot to the figure.
Generate x array
Generate y array
Use plot() to draw the graph
Use FigureCanvasTkAgg(figure,win) to put figure on the win (window)
Use get_tk_widget().pack() to place figure on the win (window)
Build close_win function to end the window
Build Button component and give a string to text, and use command to call the function
Use pack to arrange Button on bottom side
Use mainloop() to keep window running for monitoring and handling events
這個範例說明如何整合matplotlib的繪圖到tkinter的圖形介面上。
#1. 引入tkinter (python 3)
#2. 引入matplotlib函式庫
#3. 引入FigureCanvasTkAgg: 將matplotlib的figure放在tk視窗上
#4. 引入Figure: Top level container for all plot elements. 將plot放在figure容器裡
#5 建立一個名為win的新視窗
#6. 視窗格式: 標題 Title()
#7. 視窗格式: 設定視窗啟動時的大小與位置 geometry(“寬x長+x位移+y位移”)
#8. 視窗格式: 設定視窗最大尺寸 maxsize(int長,int寬)
#9. 建立一個figure圖像,figsize=(寬度英吋,高度英吋);dpi=每英吋多少像素(https://matplotlib.org/api/figure\_api.html)
#10. 新增一個subplot子圖到figure中
#11. 建立x陣列
#12. 建立y陣列
#13. 使用plot()方法繪圖
#14. 使用FigureCanvasTkAgg(figure,win)將figure加在win視窗上
#15. 使用get_tk_widget().pack()將figure在win視窗上做布局(fill=tk.X x方向填滿,fill=tk.Y x方向填滿,fill=tk.BOTH X、Y方向接填滿)
#16. 建立函數close_win函數: 結束win視窗
#17. 建立Button元件,按鍵文字 Text = “”
#18. Button元件布局 pack(side=’bottom’) 靠下
#19. mainloop()在使用者關閉視窗之前持續偵測視窗並處理事件
1 | import tkinter as tk |
win.title(“tkinter plt”)
win.geometry(“700x650+10+10”)
win.maxsize(1000,700)
#plot
1 | figure=Figure(figsize=(3,3),dpi=100) |
plot.plot(x, y, color=”blue”, marker=”x”, linestyle=”:”)
canvas=FigureCanvasTkAgg(figure,win)
canvas.get_tk_widget().pack(side=tk.RIGHT, fill=tk.Y, expand=1) #fill=tk.BOTH/X/Y
#plot1
1 | figure1=Figure(figsize=(3,3),dpi=100) |
plot1.plot(x1, y1, color=”red”, marker=”o”, linestyle=”–”)
canvas1=FigureCanvasTkAgg(figure1,win)
canvas1.get_tk_widget().pack(side=tk.LEFT, fill=tk.Y, expand=1) #fill=tk.BOTH/X/Y
def close_win():
win.destroy()
close_btn=tk.Button(win,text=”Close”,command=close_win)
close_btn.pack(side=’bottom’)
win.mainloop()
We will share more tutorial videos with people who want to learn LabVIEW and Python welcome to subscribe this channel.
未來會陸續更新影片,讓想學習LabVIEW和Python的朋友可以看影片學習,歡迎訂閱此頻道。
其他網址/related websites:
https://labview-tech.blogspot.com/
https://fishark.pixnet.net/blog
email: jacklee3633 @gmail.com
Line: lvnet