我正在尝试制作一个绘制不同朱莉娅集的程序,并且首先尝试绘制曼德尔布罗特集。然而,当我尝试在 tkinter 画布上绘制某些内容时,什么也没有显示。我也尝试过添加简单的矩形,但它不起作用
from tkinter import *
SIZE = 600
class Fractal:
zoom_list = []
def __init__(self, master):
master.title("Julia Set")
self.canvas = Canvas(master, width=SIZE, height=SIZE, bg="#FFFFFF")
self.canvas.grid(rowspan=11, column=1, sticky=NW)
self.img = PhotoImage(width=SIZE, height=SIZE)
self.canvas.create_image((50, 50), image=self.img, state="normal")
self.plot_button = Button(master, text="plot fractal")
self.zoom_out_button = Button(master, text="zoom out")
self.input_field = Entry(master, fg="black", bg="white", width=50)
self.plot_button.grid(row=10, column=2, sticky=W)
self.zoom_out_button.grid(row=9, column=2, sticky=W)
self.input_field.grid(row=8, column=2, sticky=W)
def is_bounded(self, a, b):
"""Checks if a complex number is in the Mandelbrot set returning boolean based on outcome"""
a = a / 300 - 2.5
b = b / 300 - 1.5
c = complex(a, b)
z = 0
for i in range(200):
if abs(z) > 2:
return False
z = pow(z, 2) + c
return True
def plot_fractal(self):
"""Adds a plot of the mandelbrot set to img and returns None"""
for y in range(SIZE):
for x in range(SIZE):
if self.is_bounded(self, x, y):
self.canvas.put("#2596be", (x, y))
def main():
root = Tk()
root.geometry("800x600+100+100")
app = Fractal(root)
root.mainloop()
if __name__ == '__main__':
main()
我还尝试绘制简单的矩形或在画布上为点着色,但它不起作用
但是,当我尝试在 tkinter 画布上绘制某些内容时,什么也没有 出现了
@Bas van der Linden 说,您需要通过在第 50 行添加
plot_fractal
) 来调用 app.plot_fractal(
方法。
@jasonharper 说,
Canvas
没有 .put()
方法。正如 @acw1668 所说,将第 41 行的 self.canvas 替换为 self.img
。
@acw1668 说,删除第 40 行上的
self.
。
在第 50 行添加此
app.plot_fractal()
片段:
def plot_fractal(self):
"""Adds a plot of the mandelbrot set to img and returns None"""
for y in range(SIZE):
for x in range(SIZE):
if self.is_bounded(x, y):
self.img.put("#2596be", (x, y))
def main():
root = Tk()
root.geometry("800x600+100+100")
app = Fractal(root)
app.plot_fractal()
root.mainloop()
屏幕截图:等待至少 15 秒或更长时间才能看到主窗口弹出。