# L-31 MCS 260 Mon 5 Nov 2007 : guisample.py # # GUI to sample a user given function. from Tkinter import * from math import * class SampleFun(): """ GUI to sample f(x) over [a,b] """ def __init__(self,wdw): "defines layout and data of GUI" wdw.title("Plot Expressions") self.L1 = Label(wdw,text="f(x) =") self.L1.grid(row=0) self.f = Entry(wdw) # for f(x) self.f.grid(row=0,column=1,\ columnspan=5,sticky=W+E+N+S) self.L2 = Label(wdw,text="a =") self.L2.grid(row=1,column=0) self.a = Entry(wdw) # for a self.a.grid(row=1,column=1) self.L2 = Label(wdw,text="b =") self.L2.grid(row=1,column=2) self.b = Entry(wdw) # for b self.b.grid(row=1,column=3) self.L3 = Label(wdw,text="N =") self.L3.grid(row=1,column=4) self.n = Entry(wdw) # for N self.n.grid(row=1,column=5) self.d = 400 # dimension of canvas self.c = Canvas(wdw,width=self.d,\ height=self.d,bg='white') self.c.grid(row=3,columnspan=6) self.s = Button(wdw,text="sample and plot",\ command=self.Show) self.s.grid(row=2,column=0,\ columnspan=6,sticky=W+E+N+S) self.x = [] # where sampled self.y = [] # sampled values self.P = [] # scaled points def Sample(self): "samples the function" A = float(self.a.get()) B = float(self.b.get()) N = int(self.n.get()) dx = (B-A)/(N+1) x = A self.x = [] self.y = [] for k in range(0,N): y = eval(self.f.get()) self.x.append(x) self.y.append(y) x = x + dx def ScalePt(self,x,a,b,c,d): "maps x from [a,b] into [c,d]" return (d-c)/(b-a)*(x-a) + c def Scale(self): "scales the points" A = float(self.a.get()) B = float(self.b.get()) m = min(self.y) M = max(self.y) U = 0.95*self.d L = 0.05*self.d self.P = [] for k in range(0,len(self.x)): X = self.ScalePt(self.x[k],A,B,L,U) Y = self.ScalePt(self.y[k],m,M,L,U) Y = U - Y + L # origin is topleft self.P.append((X,Y)) def Show(self): "samples, scales, and shows" self.Sample() self.Scale() self.c.delete(ALL) # refresh canvas for k in range(0,len(self.P)): self.c.create_oval(\ self.P[k][0]-6,self.P[k][1]-6,\ self.P[k][0]+6,self.P[k][1]+6,\ width=1,outline='black',fill='SkyBlue2') def main(): top = Tk() gui = SampleFun(top) top.mainloop() if __name__ == "__main__": main()