# L-7 MCS 275 Wed 30 Jan 2008 : flake.py from Tkinter import * import math class KochFlake(): """ GUI to draw a Koch flake canvas. """ def __init__(self,wdw): "determines the layout of the GUI" wdw.title('a regular n Koch flake') self.d = 400 self.n = IntVar() self.k = IntVar() self.sn = Scale(wdw,orient='horizontal',\ from_=3,to=20,tickinterval=1,\ length=self.d,variable=self.n,\ command=self.DrawFlake) self.sn.set(10) self.sn.grid(row=0,column=1) self.c = Canvas(wdw,width=self.d,\ height=self.d,bg ='white') self.c.grid(row=1,column=1) self.sk = Scale(wdw,orient='vertical',\ from_=0,to=6,tickinterval=1,\ length=self.d,variable=self.k,\ command=self.DrawFlake) self.sk.set(0) self.sk.grid(row=1,column=0) def koch(self,A,B,k): "recursive drawing of Koch curve" if(k==0): self.c.create_line(A[0],A[1],B[0],B[1],width=2) else: L = ((2*A[0]+B[0])/3.0,(2*A[1]+B[1])/3.0) R = ((A[0]+2*B[0])/3.0,(A[1]+2*B[1])/3.0) M = ((A[0]+B[0])/2.0,(A[1]+B[1])/2.0) s = math.sqrt(3)/6 T = (s*(A[1]-B[1]),s*(B[0]-A[0])) P = (M[0]-T[0],M[1]-T[1]) self.koch(A,L,k-1) self.koch(L,P,k-1) self.koch(P,R,k-1) self.koch(R,B,k-1) def DrawFlake(self,v): "Draws a regular Koch flake" cx = self.d/2 cy = self.d/2 radius = 0.4*self.d self.c.delete(ALL) n = self.n.get() k = self.k.get() t = '(' + str(n) + ',' + str(k) + ')' self.c.create_text(cx,cy,text=t,tags="text") L = [] for i in range(0,n): vx = cx + radius*math.cos(2*i*math.pi/n) vy = cy + radius*math.sin(2*i*math.pi/n) L.append((vx,vy)) for i in range(0,n-1): self.koch(L[i],L[i+1],k) self.koch(L[n-1],L[0],k) def main(): top = Tk() show = KochFlake(top) top.mainloop() if __name__ == "__main__": main()