我想在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)
你從來沒有真正調用任何繪圖命令(除添加標題,這應該是'set_title' )和'graph'看起來像'ab'是未定義的。 – tacaswell
我還沒有調用任何繪圖命令,而且ab ab未定義。我已修復它..但仍然代碼does not似乎工作.. –
什麼是「無法」意思?你有錯誤嗎?程序崩潰了嗎? –