# Mandelbrot Fractal using Tkinter
# FB36 - 20130706
from __future__ import division
import Tkinter
from Tkinter import *
import math

WIDTH = 100; HEIGHT = 100
xa = -2.0; xb = 2.0
ya = -2.0; yb = 2.0
maxIt = 256

window = Tk()
canvas = Canvas(window, width = WIDTH, height = HEIGHT, bg = "#000000")
img = PhotoImage(width = WIDTH, height = HEIGHT)
canvas.create_image((0, 0), image = img, state = "normal", anchor = Tkinter.NW)

sgn = lambda x: -1 if x < 0 else 1

n = 100
for r in range( n):
	k = (2 * r / ( n - 1 )) - 1 
	for ky in range(HEIGHT):
	    for kx in range(WIDTH):
		x=xa + (xb - xa) * kx / WIDTH
		y= ya + (yb - ya) * ky / HEIGHT
		try:
			c = complex(x,y)**(sgn(k)*abs(k)**3)#(math.sin(k*math.pi/2))
			z = complex(0.0, 0.0)
			for i in range(maxIt):
				z = z * z + c
				if abs(z) >= 2.0:
					rd = hex(i % 4 * 64)[2:].zfill(2)
					gr = hex(i % 8 * 32)[2:].zfill(2)
					bl = hex(i % 16 * 16)[2:].zfill(2)
					img.put("#" + rd + gr + bl, (kx, ky))
					break
		except: 
			pass
		
	img.write( "m2/r{0}.png".format( r ), format="png" )

canvas.pack()
mainloop()

