업무에 파이썬 활용할 줄 알기
Day 18 | 중급 | 터틀 & 그래픽 사용자 인터페이스 (GUI) 본문
Day 18 | 중급 | 터틀 & 그래픽 사용자 인터페이스 (GUI)
SEO 데이터분석가 2024. 1. 2. 18:1018일차 목표: 오늘의 최종 결과물
Turtle Graphics, Tuples and Importing Modules
터틀 그래픽 이해하기 및 문서 사용법
from turtle import Turtle (turtle 모듈에서 Turtle 클래스를 임포트한다)
원하는 기능을 구글링하여 모듈의 도큐먼트를 필요에 따라 참고한다
TK color specification > Tk interface > 파이썬에서 GraphinalUser Interface를 구현하기 위한 방법중의 하나이다
애플리사 전에 MS DOS와 같은 text interface였었다
The text interfaces accept text commands and the graphical user interfaces can
show images and allows you to click and drag and do all of those things by looking instead of just typing commands.
And tkinter is what the turtle module actually relies on under the hood to create these graphics,
like our turtle showing up here.
애플 리사 컴퓨터는
그래픽 사용자 인터페이스를 도입한 최초의 컴퓨터였습니다
마우스로 가리키고 클릭할 수 있었죠
이는 당시에 매우 큰 변화였습니다
하지만 그 이전에는 파이썬을 사용할 때 쓰는
MS-DOS 또는 콘솔과 같은 텍스트 인터페이스가 있었습니다
텍스트 인터페이스는 텍스트 명령어를 받지만 그래픽 사용자 인터페이스는
이미지를 표시하여 사용자가 단순히 명령어를 입력하는 대신 클릭과 드래그를 통해
눈으로 보면서 작업을 수행할 수 있도록 합니다 터틀 모듈은 실제로 시스템 밑단에서
tkinter 모듈에 의존하여 그래픽을 생성합니다
여기에 터틀이 표시되는 것처럼요

터틀 과제 1 - 정사각형 그리기
모듈 임포트하기, 패키지 설치하기, 별칭 사용하기
모듈 임포트하는 방법
# 한두번 사용하는 코드일 떄
import turtle
tim = turtle.Turtle()
# 어떤 모델로부터 무언가를 3번 이상 사용할 때 권장 방법
from turtle import Turtle
tim = Turtle()
tom = Turtle()
terry = Turtle()
# 비권장 방법
from random import *
choice([1,2,3]) #어떤 모듈에서 온건지 알 수 없음
# 모듈이름이 길 때
import turtle as t
tim = t.Turtle()
터틀 과제 2 - 점선 그리기
터틀 과제 3 - 다양한 도형 그리기
My solution
from turtle import Turtle, Screen
tim = Turtle()
tim.shape()
#어떻게 움직이는게 좋을까
#일단 forward
#right(각도)
#이 움직임을 3,4,5,6,7,8,9
color = ["#B0C4DE","#87CEEB","#008B8B","#00FA9A","#BDB76B","#FFD700","#BC8F8F"]
for i in range(3,10):
angle = 360 / i
color_choice = color[i-3]
for _ in range(i):
tim.color(color_choice)
tim.forward(100)
tim.right(angle)
screen = Screen()
screen.exitonclick()
Angela's solution
def문을 써줌
컬러 선택을 random 모듈을 사용함
from turtle import Turtle, Screen
import random
tim = Turtle()
colors = ["#B0C4DE","#87CEEB","#008B8B","#00FA9A","#BDB76B","#FFD700","#BC8F8F"]
def draw_shape(num_sides):
angle = 360/num_sides
for _ in range(num_sides):
tim.forward(100)
tim.right(angle)
for shape_side_n in range(3,10):
tim.color(random.choice(colors))
draw_shape(shape_side_n)
screen = Screen()
screen.exitonclick()
터틀 과제 4 - 무작위 행보 구현하기
My solution
from turtle import Turtle, Screen
import random
tim = Turtle()
colors = ["#B0C4DE","#87CEEB","#008B8B","#00FA9A","#BDB76B","#FFD700","#BC8F8F"]
angles = [0, 90, 180, 270]
#무작위행보구현
##아무컬러세팅 > random.choice(colors)
##아무위치로 세팅(좌우위아래) > 이걸 어떻게 구현할 수 있지? right(0, 90, 180, 270) > random.choice(angles)
##forward
##위 행동을 몇번이나 반복?
tim.pensize(5)
for i in range(50):
tim.color(random.choice(colors))
tim.right(random.choice(angles))
tim.forward(30)
screen = Screen()
screen.exitonclick()
Angela's solution
right대신 setheading 사용
from turtle import Turtle, Screen
import random
tim = Turtle()
colors = ["#B0C4DE","#87CEEB","#008B8B","#00FA9A","#BDB76B","#FFD700","#BC8F8F"]
angles = [0, 90, 180, 270]
tim.pensize(5)
tim.speed("fastest")
for i in range(200):
tim.color(random.choice(colors))
tim.setheading(random.choice(angles))
tim.forward(30)
screen = Screen()
screen.exitonclick()
파이썬 튜플 및 임의의 RGB 색상 생성하기
But we have to tap into the actual turtle module and not the turtle object,
and then change the color mode for that module.
??
Now we've got three random numbers,
one each representing each of the color spaces,
and then we can generate our tuple. Here's the challenge for you.
See if you can return from this function
a tuple that consists of the three random integers, r, g and b,
and then use that random color to color the turtle drawing instead of this broken
code which relied on that previous list of colors.
t.colormode가 여전히 이해가 안감..
안젤라가 저부분이 tricky해서 challenge과제로 주지 않았다고 했는데..?
My solution
import turtle as t
from turtle import Screen
import random
tim = t.Turtle()
t.colormode(255)
def random_color():
r = random.randint(0,255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
angles = [0, 90, 180, 270]
tim.pensize(5)
tim.speed("fastest")
for i in range(200):
tim.color(random_color())
tim.setheading(random.choice(angles))
tim.forward(30)
screen = Screen()
screen.exitonclick()
Angela's solution
(r, g, b)를 random_color 변수에 할당함
import turtle as t
from turtle import Screen
import random
tim = t.Turtle()
t.colormode(255)
def random_color():
r = random.randint(0,255)
g = random.randint(0, 255)
b = random.randint(0, 255)
random_color = (r, g, b)
return random_color
angles = [0, 90, 180, 270]
tim.pensize(5)
tim.speed("fastest")
for i in range(200):
tim.color(random_color())
tim.setheading(random.choice(angles))
tim.forward(30)
screen = Screen()
screen.exitonclick()
터틀 과제 5 - 스피로그래프(Spirograph) 그리기
원그리는방법
원을 반복적으로 그리고, 조금씩 기울기를 바꾸는 방법
My solution
import turtle as t
from turtle import Screen
import random
tim = t.Turtle()
tim.speed("fastest")
t.colormode(255)
def random_color():
r = random.randint(0,255)
g = random.randint(0, 255)
b = random.randint(0, 255)
random_color = (r, g, b)
return random_color
def spirograph(num_of_gap):
for i in range(int(360 / num_of_gap)):
tim.color(random_color())
tim.circle(100)
tim.right(num_of_gap)
spirograph(30)
screen = Screen()
screen.exitonclick()
Angela's solution
from turtle import Screen 지우고 import turtle as t 로 통일했음
heading, setheading 함수를 사용함
import turtle as t
import random
tim = t.Turtle()
tim.speed("fastest")
t.colormode(255)
def random_color():
r = random.randint(0,255)
g = random.randint(0, 255)
b = random.randint(0, 255)
color = (r, g, b)
return color
def draw_spirocircle(size_of_gap):
for _ in range(int(360/size_of_gap)):
tim.color(random_color())
tim.circle(100)
tim.setheading(tim.heading() + size_of_gap)
draw_spirocircle(10)
screen = t.Screen()
screen.exitonclick()
허스트 페인팅 프로젝트 1부 - 이미지에서 RGB 값 추출하기
colorgram 안깔려있는데..? 파이참에 없는 패키지 임포트 텍스트 입력했을 때 오류 뜨면 다운로드하는 방법
파이참에서 패키지 다운로드 하는 방법
Windows: File → Settings
My solution
import colorgram
colors = colorgram.extract('ezgif.com-webp-to-jpg-converter.jpg', 10)
hirst_color = []
for i in range(10):
extract_color = colors[i]
rgb = extract_color.rgb
hirst_color.append(rgb)
print(hirst_color)
print(type(hirst_color[0]))
Angela's solution
for문에 바로 리스트 사용하는거를 자꾸 활용을 못하고 있다..
import colorgram
colors = colorgram.extract('ezgif.com-webp-to-jpg-converter.jpg', 10)
rgb_colors = []
for color in colors:
rgb_colors.append(color.rgb)
print(rgb_color)
Angela's solution (tuple형태로)
import colorgram
colors = colorgram.extract('ezgif.com-webp-to-jpg-converter.jpg', 10)
rgb_colors = []
for color in colors:
r = color.rgb.r
g = color.rgb.g
b = color.rgb.b
new_color = (r, g, b)
rgb_colors.append(new_color)
print(rgb_colors)
허스트 페인팅 프로젝트 2부 - 점 그리기
시행착오를 겪으며 알게된 주의사항
t.colormode(255)를 미리 선언해주지 않으면
정상적으로 tuple을 color 파라메터에 적용을 하더라도 아래와 같이 오류가 난다
My solution
import turtle as t
import random
color_list = [(218, 163, 112), (141, 51, 105), (246, 232, 236), (165, 169, 39), (244, 81, 58), (223, 239, 234), (234, 111, 163), (72, 197, 215), (227, 235, 238)]
tim = t.Turtle()
t.colormode(255)
tim.speed("fastest")
def draw_ten_dots():
for i in range(9):
dot_color = random.choice(color_list)
tim.dot(20, dot_color)
tim.penup()
tim.forward(50)
def move_to_upper_line():
tim.left(90)
tim.penup()
tim.forward(50)
tim.left(90)
tim.penup()
tim.forward(500)
tim.right(180)
for _ in range(10):
draw_ten_dots()
move_to_upper_line()
screen = t.Screen()
screen.exitonclick()
Angela's Solution
처음 시작위치를 조정해줌
right, left 대신 setheading 사용
100번 반복문을 한번만 사용
나는 def문으로 만들어 준걸 여기서는 10번째에 윗줄로 옮겨갈수 있는 if문을 사용함
penup()을 제일 위에서 한번만 사용
import turtle as t
import random
color_list = [(218, 163, 112), (141, 51, 105), (246, 232, 236), (165, 169, 39), (244, 81, 58), (223, 239, 234), (234, 111, 163), (72, 197, 215), (227, 235, 238)]
tim = t.Turtle()
t.colormode(255)
tim.speed("fastest")
tim.hideturtle()
tim.penup()
tim.setheading(225)
tim.forward(300)
tim.setheading(0)
number_of_dots = 100
for dot_count in range(1, number_of_dots + 1):
tim.dot(20, random.choice(color_list))
tim.forward(50)
if dot_count % 10 == 0:
tim.setheading(180)
tim.forward(50)
tim.setheading(90)
tim.forward(50)
tim.setheading(180)
tim.forward(450)
tim.setheading(0)
screen = t.Screen()
screen.exitonclick()
'Python > [Udemy] 100개의 프로젝트로 Python 개발 완전 정복' 카테고리의 다른 글
Day20 | 중급 | 뱀 게임 만들기 1편: 애니메이션 & 좌표 (0) | 2024.01.04 |
---|---|
Day19 | 중급 | 인스턴스, 상태 및 고차함수 (0) | 2024.01.03 |
Day17 | 중급 | 퀴즈 프로젝트와 OOP의 장점 (0) | 2023.12.28 |
Day16 | 중급 | 객체 지향 프로그래밍(OOP) (0) | 2023.12.27 |
Day15 | 중급 | 커피 머신 프로젝트 (0) | 2023.12.26 |