파이썬_실전 프로젝트

간단한 계산기 만들기-1

파이썬의 tkinter 모듈을 이용하여 간단한 계산기를 만들어 보도록 하겠습니다.

 

파이썬을 실행하고, tkinter 모듈을 불러와 주세요.

import tkinter

모듈이 없다고 나오면, 따로 설치할수도 있지만, anaconda 소프트웨어를 설치하시는게 편리합니다.

 

빈화면 생성

import tkinter as tk

calc = tk.Tk()
calc.mainloop()

 

이름,크기 설정

 

import tkinter as tk

calc = tk.Tk()
calc.title("Calculator")
calc.geometry("300x300")

calc.mainloop()

이름은 "Calculator" 크기는 300x300으로 바꿔줬습니다.

 

출력창 추가

import tkinter as tk

calc = tk.Tk()
calc.title("Calculator")
calc.geometry("300x300")

display = tk.Entry(calc, width=20) # display라는 이름의 출력창 추가, 폭 20
display.pack()                     # 위치를 정해주는 명령어

calc.mainloop()

숫자를 입력해보면 입력은 되는데, 엔터를 치면 아무일도 일어나지 않습니다. 이것을 엔터를 입력하면 계산이 되게 바꿔보도록 하죠.

 

 엔터키 연결
import tkinter as tk

calc = tk.Tk()
calc.title("Calculator")
calc.geometry("300x300")

def func(event):             # func 함수 작성
    print('enter pressed!')   # 임시로 문자열만 출력.

display = tk.Entry(calc, width=20)
display.pack()

calc.bind('<Return>', func)     # 엔터키(이벤트)를 func 함수로 연결.

calc.mainloop()

enter pressed!

엔터키를 입력할때마다 메세지가 출력되는것을 볼수 있습니다.

 

입력창의 값 가져오기
import tkinter as tk

calc = tk.Tk()
calc.title("Calculator")
calc.geometry("300x300")

def func(event):
    print(tk.Entry.get(display))  # 입력창에 들어있는 값을 출력해줍니다.

display = tk.Entry(calc, width=20)
display.pack()

calc.bind('<Return>', func)

calc.mainloop()

 

 3*4라고 입력을 하고, 엔터를 치면,

 콘솔창에 3*4라고 출력되는 것을 볼수 있습니다.

 

계산하기

불러온 3*4 라는 문자열을 eval() 함수로 넣어주면, 자동으로 숫자로 변환되어서 계산이 되고, 12라는 값이 출력됩니다.

import tkinter as tk

calc = tk.Tk()
calc.title("Calculator")
calc.geometry("300x300")

def func(event):
    result = eval(tk.Entry.get(display))  # eval() 함수로 계산
    print(result)

display = tk.Entry(calc, width=20)
display.pack()

calc.bind('<Return>', func)

calc.mainloop()

12

 

결과값을 입력창에 나타내기

그러면 이제 12라는 결과값을 3*4 가 있던 창으로 보내서 입력문자는 없애고, 결과값으로 바꿔보죠.

 

 3*4를 입력하고 엔터를 치면 그자리에 12가 나타나는 거죠.

명령어는 아래와 같습니다.

display.delete(0,tk.END)  # 0번째 자리부터 끝까지 삭제하는 명령어
display.insert(0,result)  # 0번째 자리에 result 변수값을 입력하는 명령어

위 두 명령어를 func 함수에 추가 해줍니다.

import tkinter as tk

calc = tk.Tk()
calc.title("Calculator")
calc.geometry("300x300")

def func(event):
    result = eval(tk.Entry.get(display))
    print(result)
    display.delete(0,tk.END)  # 내용 삭제
    display.insert(0,result)  # 새 값 입력

display = tk.Entry(calc, width=20)
display.pack()

calc.bind('<Return>', func)

calc.mainloop()

 

 버튼 추가 (=,C) 버튼,

이퀄 버튼과, 화면을 지우는 버튼을 추가해주겠습니다. 위치는 나중에 조정하기로 하죠.

import tkinter as tk

calc = tk.Tk()
calc.title("Calculator")
calc.geometry("300x300")

def calculate(event):   # func함수이름을 calculate로 바꿔줬습니다. 호출하는 부분도 같이 바꿔주세요.
    value = tk.Entry.get(display)
    if value != '':
        result = eval(value)
        print(result)
        display.delete(0,tk.END)
        display.insert(0,result)

def clear(event):            # C 버튼과 Esc 키를 위한 함수 입니다.
    display.delete(0,tk.END)  # 내용 삭제
    
display = tk.Entry(calc, width=20)
display.pack()

button_e = tk.Button(calc, text='=', width=5)  # = 버튼 추가
button_e.bind('<Button-1>',calculate)          # 버튼에 클릭 이벤트 추가
button_e.pack()

button_c = tk.Button(calc, text='c', width=5)  # C버튼추가. text속성은 버튼에 표시할 문자입니다.
button_c.bind('<Button-1>',clear)           # <Button-1> 이벤트는 마우스 왼쪽클릭 이벤트입니다.
button_c.pack()

calc.bind('<Return>', calculate)
calc.bind('<Escape>', clear)  # Esc 키도 C버튼과 통일한 기능을 하도록 연결해줬습니다.

calc.mainloop()

 이런식으로 나머지 버튼과 이벤트 등등을 추가해줄수 있습니다.

이벤트 타입은 아래 링크를 참조하세요.

https://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

 나머지 버튼은 다음 토픽에 이어서 하도록 하겠습니다.

댓글

댓글 본문
  1. nomadlife
    def clear(event): 이 줄에 탭이 들어간거 같은데 왼쪽으로 옮겨보세요. 전체코드 실행하실때 shell 보다 편집기로 파일을 만들어서 실행하는것을 추천합니다.
    대화보기
    • skghdl
      맨 마지막 코드를 똑같이 입력했는데 오류가 납니다. >>> import tkinter as tk
      >>>
      >>> calc = tk.Tk()
      >>> calc.title("Calculator")
      ''
      >>> calc.geometry("300x300")
      ''
      >>>
      >>> def calculate(event): # func함수이름을 calculate로 바꿔줬습니다. 호출하는 부분도 같이 바꿔주세요.
      ... value = tk.Entry.get(display)
      ... if value != '':
      ... result = eval(value)
      ... print(result)
      ... display.delete(0,tk.END)
      ... display.insert(0,result)
      ...
      ... def clear(event): # C 버튼과 Esc 키를 위한 함수 입니다.
      File "<stdin>", line 9
      def clear(event): # C 버튼과 Esc 키를 위한 함수 입니다.
      ^
      SyntaxError: invalid syntax
      >>> display.delete(0,tk.END) # 내용 삭제
      File "<stdin>", line 1
      display.delete(0,tk.END) # 내용 삭제
      IndentationError: unexpected indent
      >>>
      >>> display = tk.Entry(calc, width=20)
      >>> display.pack()
      >>>
      >>> button_e = tk.Button(calc, text='=', width=5) # = 버튼 추가
      >>> button_e.bind('<Button-1>',calculate) # 버튼에 클릭 이벤트 추가
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      NameError: name 'calculate' is not defined
      >>> button_e.pack()
      >>>
      >>> button_c = tk.Button(calc, text='c', width=5) # C버튼추가. text속성은 버튼에 표시할 문자입니다.
      >>> button_c.bind('<Button-1>',clear) # <Button-1> 이벤트는 마우스 왼쪽클릭 이벤트입니다.
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      NameError: name 'clear' is not defined
      >>> button_c.pack()
      >>>
      >>> calc.bind('<Return>', calculate)
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      NameError: name 'calculate' is not defined
      >>> calc.bind('<Escape>', clear) # Esc 키도 C버튼과 통일한 기능을 하도록 연결해줬습니다.
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      NameError: name 'clear' is not defined
      >>>
      >>> calc.mainloop()

      이렇게 뜨는데 도움을 받을 수 있을까요?
    버전 관리
    nomadlife
    현재 버전
    선택 버전
    graphittie 자세히 보기