" python.exe已停止工作"崩溃,FigureCanvasTkAgg.show()

时间:2016-08-22 07:28:58

标签: python matplotlib tkinter anaconda

我在Windows 7上运行带有python 3.4的Anaconda环境 canvas.show()导致我的python代码崩溃:

编辑:我的上一个示例缺少mainloop()函数,因此我从sentdex的youtube教程here中重新创建了一个更好的示例

以下是代码的简短示例:

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import tkinter as tk

LARGE_FONT = ("Verdana", 12)

class SeaofBTCapp(tk.Tk):

  def __init__(self, *args, **kwargs): 
    tk.Tk.__init__(self, *args, **kwargs)  
    container = tk.Frame(self)  
    container.pack(side="top", fill="both", expand=True)
    container.grid_rowconfigure(0, weight=1)
    container.columnconfigure(0, weight=1)

    self.frames = {}
    for F in (StartPage, GraphPage):
        frame = F(container, self)
        self.frames[F] = frame
        frame.grid(row=0, column=0, sticky="nsew")
    self.show_frame(StartPage)

  def show_frame(self, cont):  
    frame = self.frames[cont]
    frame.tkraise() 

class StartPage(tk.Frame): 

  def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent) #idk what the parent thing means 
    label = tk.Label(self, text="Start Page", font=LARGE_FONT)
    label.pack(pady=10, padx=10)    

    page_three_button = tk.Button(self, text="Graph Page", 
        command=lambda: controller.show_frame(GraphPage))
    page_three_button.pack()

class GraphPage(tk.Frame):
  def __init__(self, parent, controller):
    #initialize the tk.Frame you are about to use 
    tk.Frame.__init__(self, parent)
    #make the label so the user knows what page they are on 
    label = tk.Label(self, text="Graph Page!", font=LARGE_FONT)
    label.pack(pady=10, padx=10)

    #keep a way to get back home  
    home_button = tk.Button(self, text="Home Page", 
        command=lambda: controller.show_frame(StartPage))
    home_button.pack()

    f = Figure(figsize=(5,5), dpi=100)

    a = f.add_subplot(111) 
    a.plot([1,2,3,4,5], [5,4,3,2,1]) 

    canvas = FigureCanvasTkAgg(f, self)
    canvas.show()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

app = SeaofBTCapp()
app.mainloop()

enter image description here

不幸的是,当我点击"在线查看解决方案"什么都没弹出来。 当我注释掉canvas.show()时,程序会运行并且不会弹出错误消息。

1 个答案:

答案 0 :(得分:0)

添加from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

后,我能够重现问题

添加root.mainloop()后,没有崩溃。