您的位置:首页 > 编程语言 > Python开发

用python tkinter显示Mandelbrot图

2015-11-01 14:08 561 查看
我前面已经讲过了用Matlab显示Mandelbrot图的方法,原理在那里也说的,链接地址:/article/9796386.html, 这次就不讲了。直接贴代码(python3):

# encoding=utf-8

from tkinter import *
from random import randint

def paint(LX1, LX2, LY1, LY2):
xscale = float(canvas["width"]) / (LX2 - LX1)
yscale = float(canvas["height"]) / (LY2 - LY1)
xstep = (LX2 - LX1) / (float(canvas["width"]))
ystep = (LY2 - LY1) / (float(canvas["height"]))
x = LX1
while x < LX2:
y = LY1
while y < LY2:
c = count(complex(x, y))
if c == COUNT_LIMIT:
color = "black"
else:
color = random_color[c-1]
canvas.create_rectangle((x - LX1) * xscale, (y - LY1) * yscale,
(x - LX1) * xscale, (y - LY1) * yscale, fill=color, outline = color, tags="pic")
y += ystep
x += xstep

def count(c):
z = complex(0,0)
for i in range(COUNT_LIMIT):
z = z*z + c
if abs(z) > 2: return i
return COUNT_LIMIT

COUNT_LIMIT = 1000
LX1 = -2.0
LX2 = 2.0
LY1 = -2.0
LY2 = 2.0

random_color = []
for i in range(COUNT_LIMIT):
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)

r = "%02x" % r
g = "%02x" % g
b = "%02x" % b
random_color.append("#"+r+g+b)
window = Tk()
window.title("曼德布罗特分形")

canvas = Canvas(window, width=500, height=500, bg="white")
canvas.pack()

paint(LX1, LX2, LY1, LY2)

window.mainloop()




python的计算速度肯定与Matlab是没办法比的,运行时耐心点吧。本来还绑定一个鼠标滚动放大缩小的事件,但是python计算速度太慢了,经常卡死,就放弃了。大家可以尝试一下

如何绑定鼠标滚轮的事件,请见下一篇文章。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: