이번엔 GUI를 만들어 보겠습니다.
목차
이때 쓸 수 있는게 바로 tkinter 라이브러리 입니다. 저는 이미 갖고 있어서 받을 필요 없지만, 만약 모듈이 없다면 아래 방법으로 받으면 됩니다.
pip install tk
받았으면 위 라이브러리에서 세 가지 모듈을 사용해 창을 만들어 볼 겁니다.
저도 이건 처음 써봐서 덕지덕지 만들긴 했지만, 크게 어렵진 않았습니다. ㅎㅎ
1. 시작
먼저 윈도우 창을 만듭니다.
import tkinter
window = tkinter.Tk() #k는 소문자
window.title('제목')
window.geometry('400x400+200+200')
window.resizable(False, False)
window.iconbitmap('./icon.ico')
window.mainloop()
- window.title : 상단 바에 나오는 이름을 지정합니다.
- geometry(a x b + c + d) : 창의 크기와 창이 나타날 위치를 지정합니다. (a, b) 크기의 창을 (c, d) 위치에 나오게 합니다.
- resizable(False, False) : 창의 크기를 조절할 수 없게 합니다. 가로 세로를 따로 지정할 수 있습니다.
- iconbitmap() : 상단 바에 아이콘을 넣을 수 있습니다. 이 명령어는 ico 파일만 가능합니다.
- - iconphoto(False, tkinter.PhotoImage(file='파일 이름')) : 아이콘을 넣을 수 있는 또다른 함수입니다. ico 말고도 다른 걸 넣을 수 있습니다. False를 하면 새로 열리는 창에는 아이콘이 적용되지 않습니다.
- mainloop() : 위 과정을 렌더링 해 모니터에 띄웁니다.
2. 위젯
다음으로 창에 이것저것 넣을 수 있는 위젯이란 걸 만들어 보겠습니다.
- Label(window, text = 'txt', width='', height='') : 창에 문자열을 넣을 수 있습니다.
- Entry(window, width='', height='') : 입력창을 넣을 수 있습니다.
- - placeholder 넣는 법 : entry.insert('put something')
- Button(window, text='btn', width='', height='', command=함수) : 버튼을 눌러 함수를 작동시킵니다. 함수는 괄호를 넣지 않습니다.
그리고 위젯을 창에 넣는 방법도 세 가지가 있습니다.
- place(x=0, y=0) : 창의 x, y좌표에 위젯을 넣습니다.
- grid(row=0, column=0) : 창을 표처럼 구역을 나눠 그 행과 열에 맞춰 위젯을 넣습니다.
- pack(side='') : 창의 구역을 상하좌우로 나눕니다.
저는 이 프로젝트에선 place를 사용했는데, 좌표 간격을 유추하는데 은근 어려웠습니다.
2-1. 버튼으로 만드는 함수
간단한 예제를 통해 버튼으로 작동시킬 함수를 만들어 봅시다.
import tkinter
from tkinter import Label, Entry, Button
#from tkinter import * => 소속된 모든 모듈 호출
window = tkinter.Tk()
window.title('testing')
window.geomatry('200x200+200+200')
window.resizable(False, False)
def textor():
lbl1 = Label(window, text=ipt.get())
lbl1.pack(side='right')
ipt = Entry(window)
ipt.pack(side='left')
btn = Button(window, text='버튼', command=textor)
btn.pack(side='left')
window.mainloop()
입력창(ipt)에 아무거나 입력한 후 버튼(btn)을 누르면, 입력된 값을 받아 창에 띄우는(lbl) 간단한 예제입니다.
이 방식을 이용해 유튜브 url을 입력받아 영상을 다운 받는 프로그램을 만들어봅시다.
3. 프로젝트 2
저는 url 입력창과 작동 버튼을 넣고, 다운로드가 끝나고 나면 영상의 메타 데이터를 몇 가지 넣어보겠습니다.
노가다로 하나하나 넣느라 거의 누더기가 되었지만 그래도 알아볼 수 있기만 하면 됩니다(!).
마무리로 프로젝트 1번에서 만든 것을 통째로 함수에 넣어주고, 유튜브 url만 입력값을 받게 만들어 줍니다. 그리고 출력된 메타 데이터를 Label을 이용해 프로그램 창에 뜨도록 해주면 끝납니다.
import re, os
from glob import glob
from pytube import YouTube
import urllib.request
import tkinter
from tkinter import Label, Entry, Button
def downloader():
audio_dir = './audio/'
vidoe_dir = './video/'
url = url_in.get()#input("url : ")
yt = YouTube(url)
video = yt.streams.get_highest_resolution()
#video = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').last()
video.download(vidoe_dir)
translated = re.sub(r'[:?|/"]', '', yt.title)
thum_dir = './thumbnail/' + translated + '.jpg'
urllib.request.urlretrieve(yt.thumbnail_url, thum_dir)
#print(yt.streams.filter(only_audio=True).all())
try:
audio = yt.streams.filter(only_audio=True, file_extension='mp4')
audio.last().download(audio_dir)
audio_file = glob('./audio/*.mp4')
for fi in audio_file:
if fi.replace('mp4', 'mp3') in audio_file:
os.remove(fi.replace('mp4', 'mp3'))
os.rename(fi, fi.replace('.mp4', '.mp3'))
done = Label(window, text="all done!")
done.place(x=80, y=150)
except:
audio_error = Label(window, text="audio download failed", height=10)
audio_error.place(x=50, y=150)
if(yt.length%60 < 10):
sec = '0' + str(yt.length%60)
if(yt.length%60 >= 10):
sec = str(yt.length%60)
print('download done!')
print('제목 : ', yt.title)
print('영상 길이 : ', round(yt.length/60), ':', sec)
print('게시자 : ', yt.author)
print('게시일 : ', yt.publish_date)
print('조회수 : ', yt.views)
print('키워드 : ', yt.keywords)
print('썸네일 주소 : ', yt.thumbnail_url)
print('all done!')
vtitle = Label(window, text=yt.title, width=35)
vlength = Label(window, text=str(round(yt.length/60)) + ':' + sec, width=20)
vupload = Label(window, text=yt.author, width=20)
vdate = Label(window, text=str(yt.publish_date), width=20)
vtitle.place(x=50, y=30)
vlength.place(x=50, y=60)
vupload.place(x=50, y=90)
vdate.place(x=50, y=120)
window = tkinter.Tk()
window.title('youtube-downloader 1.0.0')
window.geometry('400x400+400+200')
window.resizable(False, False)
url_lbl = Label(window, text="url : ", width=5)
url_in = Entry(window, width=35)
btn = Button(window, text="여!", width=10, command=downloader)
url_lbl.place(x=0, y=5)
url_in.place(x=40, y=5)
btn.place(x=300, y=5)
lbl1 = Label(window, text='title : ', width=5)
lbl2 = Label(window, text='time : ', width=5)
lbl3 = Label(window, text='channel : ', width=5)
lbl4 = Label(window, text='date : ', width=5)
lbl1.place(x=0, y=30)
lbl2.place(x=0, y=60)
lbl3.place(x=0, y=90)
lbl4.place(x=0, y=120)
window.mainloop()
'장난감 > 유튜브 다운로더' 카테고리의 다른 글
유튜브 다운로더 5 - radiobutton(tkinter) (0) | 2023.05.11 |
---|---|
유튜브 다운로더 4 - 음성 파일 with moviepy (0) | 2022.08.07 |
유튜브 다운로더 3 - exe 파일 만들기 with pyinstaller (0) | 2022.07.22 |
유튜브 다운로더 1 - 유튜브 영상 추출 with pytube (0) | 2022.07.22 |
유튜브 다운로더를 직접 만들어보자 + 3.2 업데이트 (4) | 2022.07.22 |