반응형

 안녕하세요. 이번 포스팅에서는 'tkinter' 패키지를 이용해 GUI를 만들어보겠습니다.

 GUI란? 그래픽 사용자 인터페이스(graphical user interface)의 약자로, 컴퓨터를 사용하면서 화면 위의 틀이나 색상과 같은 그래픽 요소들을 기능과 용도를 나타내기 위해 고안된 컴퓨터 인터페이스라고 합니다. 

 tkinter을 이용해 새로운 윈도우 창을 만들고 몇 가지 기능들을 넣어보겠습니다. 이번 포스팅에서는 간단한 기능들만 다루고 추가적인 기능은 차후에 포스팅하도록 하겠습니다.

 

1. 윈도우 생성 및 출력

import tkinter

window = tkinter.Tk()
window.title("Bitcoding's window")
window.geometry('400x400')

window.mainloop()

 윈도우의 제목과 크기에 대해 설정하였습니다. 다른 것들은 넣은게 없기 때문에 텅 비어있는 모습입니다.

 

tkinter window

 

2. 레이블을 이용한 텍스트 출력

 레이블은 tkinter에서 텍스트를 배치하기 위해 사용합니다. 간단한 레이블을 배치해보겠습니다.

import tkinter

window = tkinter.Tk()
window.title("Bitcoding's window")
window.geometry('400x400')

lb_1 = tkinter.Label(text='안녕하세요. Bitcoding 입니다.')
lb_1.pack()

window.mainloop()

 

 '안녕하세요. Bitcoding 입니다' 라는 텍스트가 정상적으로 출력된 모습입니다. 

tkinter Label

 

3. 클릭시 작동하는 버튼 생성

 클릭시 window를 닫는 버튼을 생성해 보겠습니다.

import tkinter

def close():
    window.destroy()

window = tkinter.Tk()
window.title("Bitcoding's window")
window.geometry('400x400')

lb_1 = tkinter.Label(text='안녕하세요. Bitcoding 입니다.')
lb_1.pack()

bt_1 = tkinter.Button(text='창닫기', command = close)
bt_1.pack()

window.mainloop()

 

 close를 정의하고 command에 연결해, 버튼을 클릭하면 창이 닫히도록 했습니다. 

close window

4. 윈도우에서 입력 받기

 지금까지는 출력하는 것이었다면, 이번에는 윈도우 창에서 간단한 수식을 입력받아 계산해보겠습니다.

import tkinter

def close():
    window.destroy()

def calculate():
    lb_2.configure(text='결과: {}'.format(str(eval(entry_1.get()))))

window = tkinter.Tk()
window.title("Bitcoding's window")
window.geometry('400x400')

lb_1 = tkinter.Label(text='안녕하세요. Bitcoding 입니다.')
lb_1.pack()

bt_1 = tkinter.Button(text='창닫기', command = close)
bt_1.pack()

entry_1 = tkinter.Entry()
entry_1.pack()

bt_2 = tkinter.Button(text='계산', command = calculate)
bt_2.pack()

lb_2 = tkinter.Label()
lb_2.pack()

window.mainloop()

 

 entry 를 이용해 수식을 입력받은 뒤, 계산 버튼을 클릭해 결과를 출력합니다.

tkinter Entry

 

 이번 포스팅에서는 tkinter 패키지를 이용해 새로운 윈도우 창을 만들어서 간단하게 출력하고 수식을 입력받아 계산하여 출력하는 코드를 작성해 봤습니다. 다른 기능이나 구체적인 설정 등 추가적인 부분은 향후 포스팅 할 계획입니다. 읽어주셔서 감사합니다.

반응형

'Python > GUI - tkinter' 카테고리의 다른 글

파이썬 tkinter을 이용해 GUI 만들기 - 위젯 배치  (0) 2022.11.02

+ Recent posts