중고생을 위한 경성 프로그래밍 교육(파이썬 프로그래밍) - 5.GUI 프로그래밍
공튕기기
리스트에 저장된 공을 화면에서 튕기도록 하는 프로그램을 개발해보자.
from tkinter import *
from random import randint
def getRandomColor():
color = "#"
for j in range(6):
color += toHexChar(randint(0,15))
return color
def toHexChar(hexValue):
if 0 <= hexValue <= 9:
return chr(hexValue + ord('0'))
else: # 10 <= hexValue <= 15
return chr(hexValue -10 + ord('A'))
class Ball:
def __init__(self):
self.x = 0
self.y = 0
self.dx = 2
self.dy = 2
self.radius = 3
self.color = getRandomColor() # 랜담 색상을 얻는다.
class BounceBalls:
def __init__(self):
self.ballList = []
window = Tk()
window.title("공 튀기기")
self.width = 350
self.height = 150
self.canvas = Canvas(window, bg = "white", width = self.width, height = self.height)
self.canvas.pack()
frame = Frame(window)
frame.pack()
btStop = Button(frame, text="정지", command = self.stop)
btStop.pack(side = LEFT)
btResume = Button(frame, text="다시 시작", command = self.resume)
btResume.pack(side = LEFT)
btAdd = Button(frame, text="+", command = self.add)
btAdd.pack(side = LEFT)
btRemove = Button(frame, text="-", command = self.remove)
btRemove.pack(side = LEFT)
self.sleepTime = 100 # 슬립 시간을 설정한다.
self.isStopped = False
self.animate()
window.mainloop()
def stop(self):
self.isStopped = True
def resume(self):
self.isStopped = False
self.animate()
def add(self): # 새로운 공을 추가한다.
self.ballList.append(Ball())
def remove(self):
self.ballList.pop()
def animate(self):
while not self.isStopped:
self.canvas.after(self.sleepTime)
self.canvas.update() # self.canvas 를 업데이트 한다.
self.canvas.delete("ball")
for ball in self.ballList:
self.redisplayBall(ball)
def redisplayBall(self, ball):
if ball.x > self.width or ball.x < 0:
ball.dx = -ball.dx
if ball.y > self.height or ball.y < 0:
ball.dy = - ball.dy
ball.x += ball.dx
ball.y += ball.dy
self.canvas.create_oval(ball.x-ball.radius, ball.y-ball.radius, ball.x+ball.radius, ball.y+ball.radius, fill = ball.color, tags="ball")
BounceBalls()
실행결과
'컴퓨터 > Python' 카테고리의 다른 글
[경성 프로그래밍 교육 5일차]파이썬 프로그래밍 - 하노이 타워 (0) | 2017.08.10 |
---|---|
[경성 프로그래밍 교육 4일차]파이썬 프로그래밍 - 스도쿠GUI (0) | 2017.08.09 |
[경성 프로그래밍 교육 4일차]파이썬 프로그래밍 - 문자 빈도수 세기 (0) | 2017.08.09 |
[경성 프로그래밍 교육 2일차]파이썬 프로그래밍 - 생일 맞히기 (0) | 2017.08.08 |
[경성 프로그래밍 교육 3일차]파이썬 프로그래밍 - 회문 검사하기 (1) | 2017.08.08 |
[경성 프로그래밍 교육 3일차]파이썬 프로그래밍 - 16진수를 10진수로 변환하기 (0) | 2017.08.07 |
[경성 프로그래밍 교육 3일차]파이썬 프로그래밍 - Rational클래스 (0) | 2017.08.07 |
[경성 프로그래밍 교육 2일차]파이썬 프로그래밍 - 랜덤워크 (1) | 2017.08.06 |