코드:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
from tkinter import *
import openpyxl
from datetime import date
import pandas as pd
import xlrd
import bs4
import urllib.request
import requests
from bs4 import BeautifulSoup
 
today = date.today()
balance = 10000000
balance_2 = 10000000
get_loc = ("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_morning.xlsx")
get_wb = xlrd.open_workbook(get_loc)
get_sheet = get_wb.sheet_by_index(0)
write_loc = ("E:\\3_2\\python\\Tkinter\\stock_today\\" + str(today) + ".xlsx")
write_wb = openpyxl.Workbook()
write_sheet = write_wb.active
write_sheet.append(["company""price""balance"])
get_loc_2 = ("E:\\3_2\\python\\Tkinter\\company_list.xlsx")
df_2 = pd.read_excel(get_loc_2, sheetname=0, converters={'종목코드':str})
price_arr = []
 
def get_bs_obj(company):
    url = "https://finance.naver.com/item/main.nhn?code=" + company
    result = requests.get(url)
    bs_obj = BeautifulSoup(result.content, "html.parser")
    return bs_obj
 
def get_price(company):
    bs_obj = get_bs_obj(company)
    no_today = bs_obj.find("p", {"class""no_today"})
    blind_now = no_today.find("span", {"class""blind"})
    return blind_now.text
 
def get_up_10():
    left_balance = balance
    for i in range(111):
        left_balance -= int(get_sheet.cell_value(i, 1)) * 10
        write_sheet.append([get_sheet.cell_value(i, 0), get_sheet.cell_value(i, 1)])
 
    write_sheet['C2'= left_balance
    show_balance.configure(text="balance = " + str(left_balance))
    return
 
def get_rate_down_10():
    left_balance = balance
    for i in range(309319):
        left_balance -= int(get_sheet.cell_value(i, 1)) * 10
        write_sheet.append([get_sheet.cell_value(i, 0), get_sheet.cell_value(i, 1)])
 
    write_sheet['C3'= left_balance
    show_balance_2.configure(text="balance = " + str(left_balance))
    return
 
 
def sell_up_10():
    df = pd.read_excel(write_loc, sheetname=0)
    company = df['company'].tolist()
    for j in range(010):
        for i in df_2.index:
            if company[j] == df_2['회사명'][i]:
                company[j] = df_2['종목코드'][i]
    left_balance = df.iloc[02]
    for i in range(010):
        left_balance += int(get_price(company[i]).replace(",""")) * 10
    show_balance.configure(text="balance = " + str(left_balance))
    return
 
 
def sell_rate_down_10():
    df = pd.read_excel(write_loc, sheetname=0, )
    company = df['company'].tolist()
    for j in range(1020):
        for i in df_2.index:
            if company[j] == df_2['회사명'][i]:
                company[j] = df_2['종목코드'][i]
    print(company)
    left_balance = df.iloc[12]
    for i in range(1020):
        left_balance += int(get_price(company[i]).replace(",""")) * 10
    show_balance_2.configure(text="balance = " + str(left_balance))
    return
 
 
 
root = Tk()
root.title("stock program")
root.geometry("250x250")
 
show_today = Label(root, text = today)
up_10 = Button(root, text="buy up 10", command=get_up_10)
rate_down_10 = Button(root, text="buy rate down 10", command=get_rate_down_10)
show_balance = Label(root, text="balance = " + str(balance))
show_balance_2 = Label(root, text="balance = " + str(balance))
sell_up_10 = Button(root, text="sell up 10", command=sell_up_10)
sell_rate_down_10 = Button(root, text="sell rate down 10", command=sell_rate_down_10)
 
show_today.place(x = 150, y = 10)
up_10.place(x=10, y=100)
show_balance.place(x=10, y = 180)
show_balance_2.place(x=10, y = 200)
sell_up_10.place(x=140, y=100)
 
root.mainloop()
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

실행결과:

주식을 사기 전 각각 천만원의 계좌(balance)의 잔액이 있다.

엑셀파일이 생성,

산 주식들의 회사명과 주가, 남은 계좌의 잔액이 입력되어있다.

 

주식을 팔고 난 뒤의 계좌의 잔액을 확인할 수 있다. (포스팅 날짜는 주말이라 주가 변동이 없음)

 

설명:

get_loc = ("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_morning.xlsx")

get_wb = xlrd.open_workbook(get_loc)

get_sheet = get_wb.sheet_by_index(0)

xlrd라이브러릴 이용해서 해당 디렉토리의 엑셀파일을 가져오는 모습.

 

write_loc = ("E:\\3_2\\python\\Tkinter\\stock_today\\" + str(today) + ".xlsx")

write_wb = openpyxl.Workbook()

write_sheet = write_wb.active

write_sheet.append(["company""price""balance"])

상승주를 가져와서 엑셀파일에 저장. 아래 포스팅 참고.

Python,crawling, bs4, openpyxl, datetime, string, 상승주 가져오기

 

Python,crawling, bs4, openpyxl, datetime, string, 상승주 가져오기

코드: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 import bs4 import urllib.reque..

coding-0830.tistory.com

 

df_2 = pd.read_excel(get_loc_2, sheetname=0, converters={'종목코드':str})

작성하 엑셀파일을 다시 ead_excel()로 읽는다. converters={'종목코드':str}를 한 이유는 0으로 시작하는 종목코드를 그대로 가져오면 앞에 0이 사라지기 때문.

 

def get_bs_obj(company):

    url = "https://finance.naver.com/item/main.nhn?code=" + company

    result = requests.get(url)

    bs_obj = BeautifulSoup(result.content, "html.parser")

    return bs_obj

 

def get_price(company):

    bs_obj = get_bs_obj(company)

    no_today = bs_obj.find("p", {"class""no_today"})

    blind_now = no_today.find("span", {"class""blind"})

    return blind_now.text

주가를 가져오는 함수, 기본적인 크롤링 방법, 아래 포스팅 참고

Python,crawling, bs4,인기검색어 가져오기

 

Python,crawling, bs4,인기검색어 가져오기

코드 : 1 2 3 4 5 6 7 8 9 import bs4 import urllib.request url = "http://naver.com" html = urllib.request.urlopen(url) bsobj = bs4.BeautifulSoup(html, "html.parser") realtime_hotkeyword = bsobj.find_..

coding-0830.tistory.com

def get_up_10():

    left_balance = balance

    for i in range(111):

        price_arr.append(get_sheet.cell_value(i, 1))

        left_balance -= int(get_sheet.cell_value(i, 1)) * 10

        write_sheet.append([get_sheet.cell_value(i, 0), get_sheet.cell_value(i, 1)])

 

    write_sheet['C2'= left_balance

    write_wb.save(write_loc)

    show_balance.configure(text="balance = " + str(left_balance))

    return

위에 따로 올린 상승주 가져오기 포스팅 코드를 이용해서 미리 다운받은 엑셀파일에서 상위 열개의 주가를 가져와 각10씩 사서 balance에서 빼는 모습. 그 balance는 새로 작성하는 엑셀파일의 C2자리에 넣는다.

 

def sell_up_10():

    df = pd.read_excel(write_loc, sheetname=0)

    company = df['company'].tolist()

    for j in range(010):

        for i in df_2.index:

            if company[j] == df_2['회사명'][i]:

                company[j] = df_2['종목코드'][i]

    left_balance = df.iloc[02]

    for i in range(010):

        left_balance += int(get_price(company[i]).replace(",""")) * 10

    show_balance.configure(text="balance = " + str(left_balance))

    return

다시 되파는 코드, 상당히 골치 아팠다. 아침에 검색할 때와 장 마감후 검색하는 급등주는 서로 다르기 때문에 아침에 검색해서 샀던 주식을 따로 일일이 검색하여 가격을 받아와야하기 때문.

일단 미리 다운받았던 상장주식의 정보가 모두 들어있는 엑셀파일에 있는 회사명과 내가 산 주식의 회사명이 일치 한다면 해당 회사명을 종목코드로 바꿔주는 작업을 한 뒤, get_price()를 이용하여 주가를 가져온다.

이 때 주가는 86,000 처럼 중간에 콤마가 붙어있기 때문에 replace()함수를 이용하여 콤마를 없애준다. 

그 후 다시 10주씩 판다는 가정하에, 잔액에 더해준다. 그리고 라벨을 업데이트된 잔액으로 바꾼다. 이는 아래 포스팅 참고.

Python, Tkinter, 화씨에서 섭씨로 바꾸기

 

Python, Tkinter, 화씨에서 섭씨로 바꾸기

코드: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from tkinter import* #function which actions when the button is pushed def convert(): f = float(ent.get()) tmp = float(5 *..

coding-0830.tistory.com

 이 하 코드는 기본적인 Tkinter라이브러리 사용방법이니 바로 위 포스팅 다시 참고.

 

'Python > Tkinter' 카테고리의 다른 글

Python, Tkinter, 현재 주가 가져오기  (0) 2019.10.04
Python, Tkinter, 화씨에서 섭씨로 바꾸기  (0) 2019.10.04

코드:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import bs4
import urllib.request
import openpyxl
from datetime import date
import string
 
today = date.today()
= []
= []
= []
def get_company():
    url = "https://finance.naver.com/sise/sise_rise.nhn?sosok=1"
    html = urllib.request.urlopen(url)
    bsobj = bs4.BeautifulSoup(html, "html.parser")
    tltle = bsobj.find_all("a", {"class""tltle"})
    for i in tltle:
        a.append(i.text)
    return
 
def get_price():
    url = "https://finance.naver.com/sise/sise_rise.nhn?sosok=1"
    html = urllib.request.urlopen(url)
    bsobj = bs4.BeautifulSoup(html, "html.parser")
    price = bsobj.find_all("td", {"class""number"})
    for i in price:
        b.append(i.text)
    for index, value in enumerate(b):
        if index%10 == 0:
            c.append(value.replace(","""))
    return
 
 
def upload_every_morning():
    get_company()
    get_price()
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.append(["company""price"])
    for i in range(0320):
        sheet.append([a[i], c[i]])
    wb.save("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_morning.xlsx")
    return
 
def upload_every_final():
    get_company()
    get_price()
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.append(["company""price"])
    for i in range(0320):
        sheet.append([a[i], c[i]])
    wb.save("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_final.xlsx")
    return
 
upload_every_morning()
upload_every_final()
 
cs

 

실행결과:

 

 

설명:

today = date.today()

today()함수를 이용하여 오늘 날짜를 today변수에 저장

 

get_company()

get_price()

회사명과 주가를 크롤링. 자세한 설명은 아래 포스팅 참고

Python,crawling, bs4,pandas,주식 엑셀로 가져오기

 

Python,crawling, bs4,pandas,주식 엑셀로 가져오기

한국 거래소에 올라와 있는 엑셀파일을 다운받는 것을 구현해보았다. 코드: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 import requests imp..

coding-0830.tistory.com

wb = openpyxl.Workbook()

openpyxl.Workbook()함수를 이용하여 엑셀 작업 시작 (엑셀을 만드는 작업)

 

sheet = wb.active

뭔말인지 모름

 

sheet.append(["company""price"])

append()함수를 이용하여 엑셀 파일에서 이미 입력이 되어있는 셀 바로 밑 줄에 내용 추가, 현재는 빈 상태이기 때문에 가장 윗줄에 입력이 됨.

 

for i in range(0320):

      sheet.append([a[i], c[i]])

회사명이 저장되어있는 a배열과 주가가 저장되어있는 c배열의 내용을 입력.

 

wb.save("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_final.xlsx")

save()함수를 이용하여 해당 주소에 파일 저장.

 

 

코드:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from tkinter import*
import requests
from bs4 import BeautifulSoup
 
def get_bs_obj(company_code):
    url = "https://finance.naver.com/item/main.nhn?code=" + company_code
    result = requests.get(url)
    bs_obj = BeautifulSoup(result.content, "html.parser")
    return bs_obj
#bs_obj를 받아서 price를 return
def get_price(company_code):
    bs_obj = get_bs_obj(company_code)
    no_today = bs_obj.find("p", {"class""no_today"})
    blind_now = no_today.find("span", {"class""blind"})
    return blind_now.text
 
#company_codes = ["005930","000660"]
def get_Price_from_ent():
    f = ent.get();
 
    lbl_2.configure(text = str(get_price(f)))
    return
 
root = Tk()
root.title("Stock Program ")
root.geometry("540x280")
 
 
lbl_1 = Label(root, text = "Company Number")
ent = Entry(root)
lbl_2 = Label(root, text = "0")
btn = Button(root, text = "Search", command = get_Price_from_ent)
 
lbl_1.place(x = 20, y = 30)
ent.place(x = 150, y = 30)
btn.place(x = 150, y = 70)
lbl_2.place(x = 150, y = 120)
 
 
root.mainloop()
cs

실행결과:

설명:

005930은 삼성전자의 번호이다.

 

위 코드는 Python,crawling, bs4,인기검색어 가져오기

 

Python,crawling, bs4,인기검색어 가져오기

코드 : 1 2 3 4 5 6 7 8 9 import bs4 import urllib.request url = "http://naver.com" html = urllib.request.urlopen(url) bsobj = bs4.BeautifulSoup(html, "html.parser") realtime_hotkeyword = bsobj.find_..

coding-0830.tistory.com

 

Python, Tkinter, 화씨에서 섭씨로 바꾸기

 

Python, Tkinter, 화씨에서 섭씨로 바꾸기

코드: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from tkinter import* #function which actions when the button is pushed def convert(): f = float(ent.get()) tmp = float(5 *..

coding-0830.tistory.com

두 개의 내용을 합친 것이다.

코드:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from tkinter import*
 
#function which actions when the button is pushed
def convert():
    f = float(ent.get())
    tmp = float(5 * (f - 32/ 9)
    #print(tmp)
    lbl_2.configure(text = str(tmp))
    return
 
root = Tk()
root.title("temperature program")
root.geometry("230x120")
 
lbl_1 = Label(root, text = "Fahrenheit")
ent = Entry(root)
lbl_2 = Label(root, text = "Celsius")
btn = Button(root, text = "change to Celsius", command = convert)
 
lbl_1.place(x = 10, y = 20)
ent.place(x = 50, y = 20)
btn.place(x = 50, y = 40)
lbl_2.place(x = 50, y = 80)
 
root.mainloop()
 
cs

 

실행결과:

 

설명:

root = Tk()

위도우를 만들어서 root변수에 저장.

 

root.title("temperature program")

만든 윈도우에 이름을 지정.

 

root.geometry("230x120")

윈도우 창의 크기

 

lbl_1 = Label(root, text = "Fahrenheit")

Lable()함수를 이용해서 라벨 생성

 

ent = Entry(root)

Entry()함수를 이용해서 입력창 생성

 

btn = Button(root, text = "change to Celsius", command = convert)

Button()함수를 이용해서 버튼 생성, 함수는 command로 호출한다.

 

def convert():

    f = float(ent.get())

    tmp = float(5 * (f - 32/ 9)

    #print(tmp)

    lbl_2.configure(text = str(tmp))

    return

함수 생성부분,  lbl_2.configure(text = str(tmp)) configure()함수를 이용해서 두번째 라벨의 내용을 결과값으로 바꾸는 함수다.

 

lbl_1.place(x = 10, y = 20)

place()함수를 이용해서 해당 좌표에 라벨을 붙이는 코드.

 

 

 

한국 거래소에 올라와 있는 엑셀파일을 다운받는 것을 구현해보았다.

 

코드:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import requests
import pandas as pd
from io import BytesIO
 
def get_Excel(tdate):
    gen_req_url = "http://marketdata.krx.co.kr/contents/COM/GenerateOTP.jspx"
    query_str_params = {
        'name''fileDown',
        'filetype''xls',
        'url''MKD/13/1302/13020402/mkd13020402',
        'market_gubun''ALL',
        'lmt_tp''1',
        'sect_tp_cd''ALL',
        'schdate': tdate,
        'pagePath''/contents/MKD/13/1302/13020402/MKD13020402.jsp'
    }
    r = requests.get(gen_req_url, query_str_params)
    gen_req_url = 'http://file.krx.co.kr/download.jspx'
    headers = {
        'Referer''http://marketdata.krx.co.kr/mdi'
    }
    form_data = {
        'code': r.content
    }
    r = requests.post(gen_req_url, form_data, headers=headers)
    r.content
    df = pd.read_excel(BytesIO(r.content))
    file_dir = "E:/3_2/python/Crawlling/data/"
    file_name = str(tdate)+'.xls'
    df.to_excel(file_dir + file_name)
    print(tdate, " crawlling")
    return
 
for year in range(2018,2019):
    for month in range(1,13):
        for day in range(1,32):
            tdate = year * 10000 + month * 100 + day * 1
            if tdate <= 20191002:
                get_Excel(tdate)
cs

 

실행결과 :

다운받아지는 모습이다.

엑셀파일 모습이다.

 

 

수정 전

 

 

코드 :

1
2
3
4
5
6
7
from selenium import webdriver
driver = webdriver.Chrome(r"C:\Users\JW\Desktop\chromedriver_win32\chromedriver.exe")
driver.get("https://www.hansung.ac.kr/web/www/login")
driver.find_element_by_name('_58_login').send_keys('1433047')
driver.find_element_by_name('_58_password').send_keys('')
driver.find_element_by_class_name('btn_login').click()
 
cs

 

실행결과 : 안됨.

================= RESTART: C:\Users\JW\Desktop\python\1-1.py =================
Traceback (most recent call last):
  File "C:\Users\JW\Desktop\python\1-1.py", line 6, in 
    driver.find_element_by_class_name('btn_login').click()
  File "C:\Users\JW\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Users\JW\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\JW\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\JW\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".btn_login"}
  (Session info: chrome=77.0.3865.90)

 

 

수정 후

 

 

 

코드 :

1
2
3
4
5
6
7
8
from selenium import webdriver
driver = webdriver.Chrome(r"C:\Users\JW\Desktop\chromedriver_win32\chromedriver.exe")
driver.get("https://www.hansung.ac.kr/web/www/login")
driver.find_element_by_name('_58_login').send_keys('1433047')
driver.find_element_by_name('_58_password').send_keys('')
driver.find_element_by_xpath("""//*[@id="loginUnited"]/form/input[7]""").click()
 
 
cs

 

실행결과 : 로그인 성공

 

설명 : 

from selenium import webdriver

selenium모듈을 이용할 것이다.

 

driver = webdriver.Chrome(r"C:\Users\JW\Desktop\chromedriver_win32\chromedriver.exe")

크롬의 웹드라이버를 가져와 driver라는 변수에 저장.

 

driver.get("https://www.hansung.ac.kr/web/www/login")

get()함수를 이용하여 매개변수로 받은 url주소를 가져온다.

 

페이지에 들어가 검사를 통해서 id박스에 해당하는 곳을 확인했다. id가 있으니 iname으로 받아온다.

driver.find_element_by_name('_58_login').send_keys('1433047')

find_element_by_name()함수를 이용하여 id가 매개벼수인 곳을 찾고 .send_keys()함수를 이용하여 그 곳에 매개벼수를 입력해주었다.

 

driver.find_element_by_name('_58_password').send_keys('')

비밀버호도 동일하게 코딩

 

driver.find_element_by_xpath("""//*[@id="loginUnited"]/form/input[7]""").click()

수정 전에 실패했던 내용이다. find_element_by_xpath()함수를 이용하여 버튼을 찾고 click()함수를 통해서 클릭을 해준다.

xpath를 받아오는법은 

이렇게 받아오면

//*[@id="loginUnited"]/form/input[7]  이런게 복사가 된다

이 것을 이유는 모르겠지만 ''' ''' (따움표 3개씩)안에 넣어주면 된다.

 

 

 

코드 : 

1
2
3
4
5
6
7
8
9
import bs4
import urllib.request
url = "http://naver.com"
html = urllib.request.urlopen(url)
bsobj = bs4.BeautifulSoup(html, "html.parser")
realtime_hotkeyword = bsobj.find_all("span", {"class":"ah_k"})
for keyword in realtime_hotkeyword:
    print(keyword.text)
 
cs

 

실행결과 :

 

설명 : 

import bs4

import urllib.request

bs4와 request모듈을 사용한다.

 

url = "http://naver.com"

html = urllib.request.urlopen(url)

urllib.request.urlopen()함수를 이용하여 url을 html이라는 변수에 저장했다.

 

bsobj = bs4.BeautifulSoup(html, "html.parser")

bs4.BeautifulSoup(매개변수, "html.parser") 함수를 통하여 파싱을 하고 bsobj라는 변수에 저장했다. 현재에는 해당 페이지의 모든 html문서가 저장되어있는 상황. print(bsobj)로 확인가능.

 

realtime_hotkeyword = bsobj.find_all("span", {"class":"ah_k"})

인기검색어에 해당하는 곳을 찾아보면 span태그안에 class 이름이 정해져있는 것을 알 수 있다.bsobj.find_all()함수를 이용하여 인기검색어들을 realtime_hotkeyword이라는 변수에 저장.

 

for keyword in realtime_hotkeyword:

    print(keyword.text)

for문을 이용하여 모두 출력.

코드:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import turtle
= turtle.Turtle()
t.speed(50)
t.up()
t.goto(0,-200)
t.down()
t.fillcolor("red")
t.begin_fill()
t.circle(250)
t.end_fill()
= 50;
t.up()
t.goto(0,-100 - x)
t.down()
t.fillcolor("white")
t.begin_fill()
t.circle(200)
t.end_fill()
t.up()
t.goto(0,-50-x)
t.down()
t.fillcolor("red")
t.begin_fill()
t.circle(150)
t.end_fill()
t.up()
t.goto(0,0-x)
t.down()
t.fillcolor("blue")
t.begin_fill()
t.circle(100)
t.end_fill()
t.up()
t.goto(-85,70-x)
t.fillcolor("white")
t.begin_fill()
= 170
t.forward(a)
t.left(144)
t.forward(a)
t.left(144)
t.forward(a)
t.left(144)
t.forward(a)
t.left(144)
t.forward(a)
t.left(144)
t.end_fill()
 
cs

 

실행결과:

 

설명:

= turtle.Turtle()

turtle객체의 메소드인 Turtle()함수를 이용하여 trutle을 생성 후 변수 t에 저장.

 

t.speed(50)

t의 그리기 속도

 

t.up()

up()함수를 이용하여 t를 도화지에서 뗀다(?) : 그려지지 않음.

 

t.goto(0,-200)

해당 좌표로 이동

 

t.down()

down()함수를 이용하여 t를 도화지에 다시 붙인다. : 그려짐

 

t.fillcolor("red")

fillcolor()함수를 이용해서 빨간색으로 칠할 준비

 

t.begin_fill()

begin_fill()함수를 이용해서 색칠 시작

 

t.circle(200)

circle()함수를 이용해서 반지름이 200인 원 그리기

 

t.end_fill()

end_fill()함수를 이용해서 색칠 끝

 

 

 

+ Recent posts