본문 바로가기
프로그램

[파이썬] 문제 : tkinter-공 클래스를 만들어 움직이기

by 오디세이99 2023. 12. 14.
728x90
반응형

import tkinter as tk
import random

class Ball:
    def __init__(self, canvas, color, size=50):
        self.canvas = canvas            # 캔버스 객체를 저장합니다. 이 캔버스 위에 공을 그립니다.
        self.id = canvas.create_oval(10, 10, size, size, fill=color, outline="black")   # 공 생성, 색상과 크기 설정
        self.canvas.move(self.id, random.randint(0, 550), random.randint(0, 550))    # 공을 캔버스 내의 무작위 위치로 이동
        self.x = random.choice([-6, -4, -2, 2, 4, 6])    # 공의 수평 및 수직 이동 속도를 무작위로 설정
        self.y = random.choice([-6, -4, -2, 2, 4, 6])

    def move(self):
        self.canvas.move(self.id, self.x, self.y)   # 공을 현재 속도로 이동시킵니다.
        pos = self.canvas.coords(self.id)           # 현재 공의 위치를 가져옵니다.
        if pos[0] <= 0 or pos[2] >= 600:           # 공이 캔버스의 가장자리에 도달하면 이동 방향을 반대로 변경
            self.x = -self.x
        if pos[1] <= 0 or pos[3] >= 600:
            self.y = -self.y

def random_color():                                 # RGB 형식으로 임의의 색상을 생성 함수
    return f'#{random.randint(0, 255):02x}{random.randint(0, 255):02x}{random.randint(0, 255):02x}'  # 16진수 변환

def main():
    root = tk.Tk()
    root.title("Ball")
    canvas = tk.Canvas(root, width=600, height=600)
    canvas.pack()

    balls = [Ball(canvas, random_color(), random.randint(50,100)) for _ in range(10)]   # 10개의 MovingBall 객체를 생성

    def animate():
        for ball in balls:      # 모든 공을 이동시키고, 이 함수를 계속 반복 
            ball.move()
        root.after(20, animate)  # 0.02초 후 animate 함수 호출

    animate()                    # 애니메이션을 시작
    root.mainloop()              # GUI 이벤트 루프를 시작

if __name__ == "__main__":
    main()

728x90
반응형

댓글