2015-09-14 220 views
0

我想在tkinter中使用Matplotlib繪製一個圖。這裏的圖表應該繪製0到24範圍內'a'的所有值。我的代碼如下Tkinter中的Matplotlib

import math 
import matplotlib 
matplotlib.use("TkAgg") 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 
from matplotlib.figure import Figure 
from tkinter import * 

def att_func(d=0, n=0, z=0): 
# Getting User inputs from the UI 

    d = d_user.get() 
    n = n_user.get() 
    z = z_user.get() 

    a = (-9.87 * math.sin(2 * ((2 * math.pi * (d - 81))/365)) + n * z) 
    a_label.configure(text=a) 

    return (a) 

#Plotting the graph 
class App: 
    def __init__(self, master): 
     frame = tkinter.Frame(master) 
     self.nbutton_graph = tkinter.Button(frame, text="Show Graph", command=self.graph) 
     self.nbutton_graph.pack() 


     f = Figure(figsize=(5, 5), dpi=100) 
     ab = f.add_subplot(111) 
     self.line, = ab.plot(range(24)) 
     self.canvas = FigureCanvasTkAgg(f, self) 
     self.canvas.show() 
     self.canvas.get_tk_widget().pack() 

    def graph(self): 
     day_elevation_hrs = [] 
     for i in range(24): 
      day_elevation_hrs.append(att_func(i, 0, 0)[0]) 


      self.canvas.draw() 

     return 
root = tkinter.Tk() 
app = App(root) 

# User Inputs 
d_user = IntVar() 
n_user = DoubleVar() 
z_user = DoubleVar() 


nlabel_d = Label(text="Enter d").pack() 
nEntry_d = Entry(root, textvariable=d_user).pack() 

nlabel_n = Label(text="Enter n").pack() 
nEntry_n = Entry(root, textvariable=n_user).pack() 

nlabel_z = Label(text="Enter z").pack() 
nEntry_z = Entry(root, textvariable=z_user).pack() 

# Displaying results 

nlabel_a = Label(text="a is").pack() 
a_label = Label(root, text="") 
a_label.pack() 

root.mainloop() 

這裏我能夠計算出我需要的東西。但是當我嘗試繪製相同的圖像時,我無法做到。我嘗試了儘可能多的修改。但似乎是在陳舊的隊友。我相信我會在某個地方出錯。但無法弄清楚在哪裏。

當我嘗試繪製與matplotlib相同的圖形,出tkinter,它的工作原理。但是當我嘗試在tkinter的用戶界面中進行操作時,我無法執行此操作。以下是在沒有tkinter的情況下在matplotlib中繪製圖形的代碼。

import matplotlib.pylab as pl 
day_elevation_hrs=[] 
for i in range(24): 
    day_elevation_hrs.append(att_func(i, 0, 0)[0]) 

pl.title("Elevation of a in range i") 
pl.plot(day_elevation_hrs) 
+1

你從來沒有真正調用任何繪圖命令(除添加標題,這應該是'set_title' )和'graph'看起來像'ab'是未定義的。 – tacaswell

+0

我還沒有調用任何繪圖命令,而且ab ab未定義。我已修復它..但仍然代碼does not似乎工作.. –

+0

什麼是「無法」意思?你有錯誤嗎?程序崩潰了嗎? –

回答

0

This documentation顯示FigureCanvasTkAgg.__init__的第二個顯式參數應該是主。 (這真是一個關鍵字參數。)

那麼,你有沒有試圖改變該行...

self.canvas = FigureCanvasTkAgg(f, master=master) 
1

您的代碼不會像發佈一樣運行,但我可以看到兩個明確的問題。

首先,您的App是一個包含畫布的框架,但您絕不會將該框架添加到根窗口。正因爲如此,你的畫布將是不可見的。

app.pack(side="top", fill="both", expand=True) 

其次,要定義的按鈕時,顯示圖形犯了一個常見的錯誤:

您創建的App的實例後添加以下代碼。 command屬性需要參考功能。但是,您是調用graph()函數,並將結果用作command屬性的值。 self.graph

self.nbutton_graph = Tk.Button(self, text="Show Graph", command=self.graph) 

通知缺乏()

換句話說,改變這種:

self.nbutton_graph = Tk.Button(self, text="Show Graph", command=self.graph()) 

了這一點。這可能是您看到像'App' object has no attribute 'line'這樣的錯誤的原因,因爲您在完全初始化所有變量之前調用了圖函數。

+0

作出了所有更改。但仍然是相同的錯誤.. –

+0

@ Sandy.Arv:什麼是「同樣的錯誤」?你遇到了什麼錯誤? –