tkinter를 활용한 계산기만들기

  • 주요기능
    1. tkinter 활용
    2. 사칙연산
    3. “C”버튼을 누르면 초기화 시키기
    4. 잘못된 operator 입력 시 오류 발생

사칙연산2

코드

from tkinter import *

def click(key):
    if key == '=':
        try:
            result = eval(entry.get())  # entry.get() ->기입창의 텍스트를 문자열로 반환
            # 0 = entry위젯이서 첫 번째 문자 / END = entry위젯에서 마지막 컨텐츠
            entry.delete(0, END)
            entry.insert(END, str(result))
        except:
            entry.insert(END, "오류가 발생했습니다.")  # 정상적인 입력이 일어나지 않으면 오류 발생
    elif key == 'C':
        entry.delete(0, END)  # 'C'를 누르면 마찬가지로 다 지우기
    else:
        # 누른 버튼이 '='가 아니라면 마지막으로 입력한 문자 다음으로도 계속 문자를 받을 수 있도록 설정
        entry.insert(END, key)


window = Tk()
window.title("태헌의 계산기")
window.geometry("349x565")          # 생성되는 window 창의 너비x높이 설정
window.resizable(False, False)      # window창의 사이즈 조절 여부(너비, 높이)
window.configure(bg='white')


# 화면을 구성할 요소들을 작성

buttons = ['C', '/',
           '7', '8', '9', '*',
           '4', '5', '6', '-',
           '1', '2', '3', '+',
           '0', '.', '=']


entry = Entry(window, width=20, bg='white', borderwidth=0, font=('arial', 20, 'bold'),
              fg="black", insertbackground="black", justify="right")
entry.grid(row=0, column=0, columnspan=5, ipady=50)
# 하위 버튼들의 column 갯수가 5개이므로 columnspan = 5


i = 0
for button in buttons:  # for문을 통해 buttons 리스트에 있는 요소들을 하나씩 가져와 검사

    # 포문 안에서 함수정의하면 포문 돌때마다 재정의... 낭비..
    def cmd(x=button):  # 모든 버튼에 cmd함수 적용
        return click(x)

    if button.isdigit() == False:  # button가 숫자가 아니면 색깔은 노랑색
        color = "yellow"
    else:
        color = "white"

    # 예외처리로 시도해봤지만 실패
    # number인지 operator인지 판단하여 각각의 위치와 디자인을 지정
    main_button = Button(window, text=button, width=11, height=5, padx=1,
                         relief="ridge", bg=color, command=cmd)

    if button == "0":
        # 반복되는 문장들은 깔끔하게 만들 수 있으면 좋을텐데..
        button1 = Button(window, text=button, width=22,
                         height=5,  padx=6, relief="ridge", bg=color, command=cmd)
        button1.grid(row=5, column=0, columnspan=2)
    elif button == ".":
        button2 = main_button
        button2.grid(row=5, column=2)
    elif button == "=":
        button3 = main_button
        button3.grid(row=5, column=3)
    elif button == "C":
        button4 = Button(window, text=button, width=35,
                         height=5,  padx=4, relief="ridge", bg="orange", command=cmd)
        button4.grid(row=1, column=0, columnspan=3)
    elif button == "/":
        button5 = main_button
        button5.grid(row=1, column=3)
    else:
        button = main_button
        button.grid(row=(i//4)+2, column=i % 4)  # entry와 row=1 이후에 버튼이 생성됨
        i += 1


window.mainloop()

tkinter

tkinter는 GUI에 대한 표준 python 인터페이스이며 Window 창을 생성할 수 있다. Python 설치 시 기본적으로 내장되어 있는 Python 표준 라이브러리이기 때문에 간단하게 GUI 프로그램을 만들 수 있다.

tkinter 기본 구조

from tkinter import *
window = Tk()
window.mainloop()

tkinter는 파이썬에 기본 내장되어 있는 라이브러리이기 때문에 별도의 설치가 필요하지 않다. tkinter를 사용하기 위해서는 위와 같이 tkinter 모듈을 import 해주어야 한다. (Python 2에서는 Tkinter를, Python 3에서는 tkinter를 import)

tkinter 모듈을 import 한 뒤에는 Tk 클래스 객체(window)를 생성, 이 객체의 mainloop() 메서드를 호출한다.

  • Tk클래스객체명.mainloop() : 윈도우 창을 윈도우가 종료될 때까지 실행시킨다.**

여기까지 코드를 작성하면 간단하게 빈 윈도우 창을 생성할 수 있다.

제목 없음

Window 창 설정

window.title("태헌의 계산기")
window.geometry("349x565")          
window.resizable(False, False)      
window.configure(bg='white')
  • Tk클래스객체명.title(“제목”)

    -윈도우 창의 제목 설정

  • Tk클래스객체명(window).geometry(“너비x높이 + x좌표+y좌표”)

    -윈도우 창의 너비 x 높이, 초기 화면 위치의 x좌표,y좌표 설정

  • Tk클래스객체명.resizable(상하, 좌우)

    -윈도우창의 창 크기 조절 가능 여부

    -True or False로 받을 수 있다.(True = 1, False= 0 처럼 상수를 입력해도 된다.)

    -첫 번째 parameter : 너비 조절 여부 / 두 번째 parameter : 높이 조절 여부

  • Tk클래스객체명.configure()

    -configure 메서드 안의 parameter로 tkinter의 위젯들에게 여러 가지 요소들을 설정해줄 수 있다.

    -어떤 parameter가 있는지 구글링 해보았다.

    >>> root.configure().keys()
    dict_keys(['bd', 'borderwidth', 'class', 'menu', 'relief', 'screen', 'use', 'background', 'bg', 'colormap', 'container', 'cursor', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'padx', 'pady', 'takefocus', 'visual', 'width'])
    

    -내가 사용한 bg=’white’ 는 background의 color를 하얀색으로 주겠다는 의미

Geometry Manager

tkinter에서 화면에 위젯을 배치하는 방식

  • place()

    -위젯의 위치를 절대 좌표로 정하는 것 = 윈도우 크기 변경에 따라 위젯들이 변경되지 않는다.

  • pack()

    -위젯들을 부모 위젯에 패킹하여 불필요한 공간을 없앤다.

  • grid()

    -위젯들을 테이블 레이아웃에 배치하는 것

    -지정된 row와 column을 정해주어 해당 위치에 위젯이 놓이게 한다.

from tkinter import *
window = Tk()

label = Label(window, text="이름")
label.grid(row=0, column=0)

text = Entry(window, width=20, background="white")
text.grid(row=0, column=1)

button = Button(window, text="button", width=15)
button.grid(row=1, column=1)

window.mainloop()

geometry

row와 column의 위치를 간단하게 표현하면..

row=0 column = 0 row =0 column = 1 row = 0 column =2
row=1 column = 0 row=1 column = 1 row=1 column = 2
row=2 column = 0 row=2 column = 1 row=2 column = 2

가로는 column, 세로는 row, 첫 시작은 0이라고 생각하면 편할 거 같다.