我目前正在使用PhotoImage和tkinter逐像素绘制Mandelbrot集。我基本上是直接使用没有修改的算法。有没有使计算更快的方法?也许快速填充大面积的颜色,或者预先计算常数?
部分代码:
ITERATIONS = 50 WIDTH, HEIGHT = 600, 600 CENTER = (-.5, 0) DIAMETER = 2.5 def mandel(c): z = 0 for i in range(ITERATIONS): z = z**2 + c if abs(z) > 2: return i return ITERATIONS root = Tk() canvas = Canvas(root, width=WIDTH,height=HEIGHT) canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal") real = CENTER[0] - 0.5 * DIAMETER imag = CENTER[1] - 0.5 * DIAMETER def color(i): colors = ("#0000AA", "#88DDFF", "#FF8800", "#000000") if i == ITERATIONS: return colors[-1] else: choice = (i//2) % len(colors) return colors[choice] for x in range(WIDTH): for y in range(HEIGHT): i = mandel(complex(real, imag)) img.put(color(i), (x, HEIGHT-y)) imag += DIAMETER / HEIGHT imag = CENTER[1] - 0.5 * DIAMETER real += DIAMETER / WIDTH mainloop()
一次设置一个像素可能是减速的主要来源。而不是为每个像素调用put,而是计算整个像素行或整个像素矩阵,然后在循环结束时调用一次。
您可以在其他位置找到示例:https : //web.archive.org/web/20170512214049/http : //tkinter.unpythonic.net : 80/wiki/PhotoImage#Fill_Many_Pixels_at_Once