Matplotlib繪圖嵌入Tkinter窗口的三方法

參考官方文檔的一些示例,對其進行補充,總結了三種方法。

使用其中一種方法時,將另外兩種方法屏蔽即可:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 29 11:13:17 2019

@author: Administrator三種把畫圖放到tkinter界面的方法,改進自官方文檔
"""
import tkinter
#-------------設置
import matplotlib
matplotlib.use('Agg')   #該模式下繪圖無法顯示,plt.show()也無法作用
#-------------
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

import numpy as np

root = tkinter.Tk()
root.wm_title("Embedding in Tk")
# 1. 用matplotlib.figure->Figure畫圖---------------------------------------
#fig = Figure(figsize=(5, 4), dpi=100)
#fig_plot = fig.add_subplot(111)
#t = np.arange(0, 3, .01)
#fig_plot.plot(t, 2 * np.sin(2 * np.pi * t))
#----------------------------------------------------------------------
# 2. 用pyplot.subplots畫圖-------------------------------------------------
#fig, axs = plt.subplots(1, 3, figsize=(5, 4), sharey=True)
#data = {'apples': 10, 'oranges': 15, 'lemons': 5, 'limes': 20}
#names = list(data.keys())
#values = list(data.values())
#axs[0].bar(names, values)
#axs[1].scatter(names, values)
#axs[2].plot(names, values)
#fig.suptitle('Categorical Plotting')
#--------------------------------------------------------------------
# 3. 用pyplot.figure畫圖-------------------------------------------------
fig = plt.figure(figsize=(5, 4), tight_layout=True)
ax = fig.add_subplot(111)
ax.plot(np.arange(0, 1e6, 1000))
ax.set_ylabel('YLabel0')
ax.set_xlabel('XLabel0')
for tick in ax.get_xticklabels():
    tick.set_rotation(90)
#fig.align_labels()  # same as fig.align_xlabels(); fig.align_ylabels()

#------------------------------------
canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

#matplotlib工具條---------------------------------
#toolbar = NavigationToolbar2Tk(canvas, root)
#toolbar.update()
#canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

def on_key_press(event):
    print("you pressed {}".format(event.key))
    key_press_handler(event, canvas, toolbar)


canvas.mpl_connect("key_press_event", on_key_press)

def _quit():
    print('quit')
    root.quit()     # stops mainloop
    root.destroy()  # this is necessary on Windows to prevent
                    # Fatal Python Error: PyEval_RestoreThread: NULL tstate

button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)

tkinter.mainloop()
# If you put root.destroy() here, it will cause an error if the window is
# closed with the window manager.

 

發佈了24 篇原創文章 · 獲贊 26 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章