오래 전, 라떼 시절 만들었던 파이썬 코드를 Chat GPT를 이용하여 개선해 보았다.
Python 2.X 시절 만든 코드를 3.X로 바꾸면서 저장 기능 까지 추가 하였다.
[원본 코드]
https://chobocho.tistory.com/2460823
[개선 코드]
from tkinter import *
import math
import random
from PIL import Image, ImageDraw
RADIAN = math.pi / 180
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return r, g, b
def draw_tree(start_x, start_y, angle, length, depth, image_draw=None):
if depth == 0:
return
scale = int(depth/12) + 1
end_x = start_x + length * scale * math.cos(angle * RADIAN)
end_y = start_y - length * scale * math.sin(angle * RADIAN)
image_draw.line([start_x, start_y, end_x, end_y], width=depth, fill=random_color())
draw_tree(end_x, end_y, angle + random.randint(10, 30), length * random.uniform(0.8, 0.9), depth - 1, image_draw)
draw_tree(end_x, end_y, angle - random.randint(10, 30), length * random.uniform(0.8, 0.9), depth - 1, image_draw)
def draw_new_tree():
myCanvas.delete("all") # Clear the canvas
image = Image.new("RGB", (800, 600), "white")
image_draw = ImageDraw.Draw(image)
draw_tree(400, 550, 90, 70, 12, image_draw)
image.save("fractal_tree.png", "PNG") # Save the image as PNG
photo = PhotoImage(file="fractal_tree.png")
myCanvas.create_image(0, 0, image=photo, anchor=NW)
myCanvas.photo = photo
if __name__ == "__main__":
root = Tk()
root.title("프랙탈 나무")
root.geometry("800x600")
myCanvas = Canvas(width=800, height=600)
draw_button = Button(text="새로운 나무 그리기", command=draw_new_tree)
draw_button.pack()
myCanvas.pack()
root.mainloop()