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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值