簡體   English   中英

Tkinter中的Matplotlib

[英]Matplotlib in Tkinter

我試圖在tkinter中使用Matplotlib繪制圖形。 此處,該圖應繪制0-24范圍內的所有“ a”值。 我的代碼如下

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的UI中執行此操作時,我無法進行操作。這是在沒有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)

您的代碼不會按發布的方式運行,但是我可以看到兩個明確的問題。

首先,您的App是一個包含畫布的框架,但是您永遠不會將其添加到根窗口中。 因此,您的畫布將不可見。

創建App實例后,添加以下代碼:

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

其次,在定義用於顯示圖形的按鈕時,您經常犯錯誤。 command屬性引用一個函數。 但是,您正在調用 graph()函數,並將結果用作command屬性的值。

換句話說,更改此:

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

對此:

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

注意self.graph之后缺少() 這可能是為什么看到諸如'App' object has no attribute 'line''App' object has no attribute 'line'錯誤'App' object has no attribute 'line' ,因為在完全初始化所有變量之前調用了graph函數。

此文檔顯示FigureCanvasTkAgg.__init__的第二個顯式參數應該是主參數。 (這實際上是一個關鍵字參數。)

因此,您是否嘗試過將該行更改為...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM