在Tkinter

时间:2017-09-20 21:42:53

标签: python matplotlib tkinter

我有matplotlib脚本,它读取Excel文件并绘制它。 (作为MATPLOT)

我做了另一个python脚本看起来像一个普通的程序(topmenu,statusbar ..)(作为GUI)

我想在GUI中显示MATPLOT。有没有办法调用MATPLOT中的所有脚本在GUI中运行?就像将视频嵌入到另一个网站一样。

root = Tk()
root.geometry("800x600")

#MENU
topMenu = Menu(root)
root.config(menu=topMenu)

loadMenu = Menu(topMenu, tearoff=0)
topMenu.add_cascade(label="File", menu=loadMenu)
loadMenu.add_command(label="Import New", command=doNothing)
loadMenu.add_command(label="Show 'Filter' Menu" , command=showOptions)
loadMenu.add_separator()
loadMenu.add_command(label="Exit", command=root.quit)

#GRAPH
#

#StatusBar
status = Label(root, text="File Name:", bd=1, relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM, fill=X)

root.mainloop()

1 个答案:

答案 0 :(得分:1)

如何在tkinter框架中嵌入matplotlib图

该方法提供了子类tk.Framematplotlib.figure.Figure,以便将代码重新用于其他目的。

它会创建一个tkFrame,所有样板都可以接受并显示matplotlib Figure
然后,它会创建Figure(再次,可以修改和扩展),并将其嵌入上面创建的tk.Frame中。
最后,它启动tk.mainloop

import matplotlib
import tkinter as tk

matplotlib.use('TkAgg')
# from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure


class GraphPage(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.title_label = tk.Label(self, text="Graph Page Example")
        self.title_label.pack()
        self.pack()

    def add_mpl_figure(self, fig):
        self.mpl_canvas = FigureCanvasTkAgg(fig, self)
        self.mpl_canvas.show()
        self.mpl_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        self.toolbar = NavigationToolbar2TkAgg(self.mpl_canvas, self)
        self.toolbar.update()
        self.mpl_canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)


class MPLGraph(Figure):

    def __init__(self):
        Figure.__init__(self, figsize=(5, 5), dpi=100)
        self.plot = self.add_subplot(111)
        self.plot.plot([1, 2, 3, 4, 5, 6, 7], [4, 3, 5, 0, 2, 0, 6])


fig = MPLGraph()

root = tk.Tk()
graph_page = GraphPage(root)
graph_page.add_mpl_figure(fig)

root.mainloop()

matplotlib Figure embedded in tkinter Frame

tutorial video from which this code was derived