2016-08-22 79 views
0

我運行的蟒蛇環境蟒蛇3.4,在Windows 7 canvas.show()引起我的Python代碼崩潰:「python.exe已停止工作」 撞車,FigureCanvasTkAgg.show()

編輯:我最後一個例子是缺少主循環()函數,所以我重新從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()時,程序運行並且錯誤消息不會彈出。

+0

它與Tkinter有什麼關係? –

+0

我正在嘗試爲matplotlib使用tkagg後端。你需要一個tk.Tk()實例傳遞給figurecanvastkagg,並且崩潰我的程序的那一行是figurecanvastkagg.show() – Julian

+0

'root.mainloop()'丟失。 –

回答

0

我能夠加入from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

加入root.mainloop()沒有崩潰後後重現該問題。