[파이썬 연습] 파이썬으로 계산기 만들기 Tkinter
Python과 Tkinter 패키지을 이용하여 간단한 계산기를 만듭니다.
목차:
1. Tkinter 패키지 설치
2. 계산기 예제
## tkinter를 tk로 선언
import tkinter as tk
## Tk init
root = tk.Tk()
## GUI window title, size
root.title("Calculator")
root.geometry("250x260")
## GUI Frames
# display frames
frame_display = tk.Frame()
frame_display.pack()
# btn frames
frame_btns = tk.Frame()
frame_btns.pack()
# font display, btn
font = ("Courier", 30, "bold")
font_nums = ("Courier", 12, "bold")
# display setup
display = tk.Entry(frame_display, width=45, justify='right', font=font)
display.pack()
# globals
global num_operator
num_operator = []
## btn clicked insert number on display
def btn_click(num):
display.insert(tk.END, num)
## display, list clear
def btn_allclear():
print("Clear Numbers")
global num_operator
num_operator.clear()
display.delete(0, tk.END)
## 계산 (def main)
def btn_cal(button):
# 연산자 [더하기 빼기 나누기 곱하기]
operators = ['+', '-', '/', '*']
# Display의 숫자와 연산자를 같이 List에 담기 ex : [1+] or [2-] or [3/]
num_operator.append(display.get()+button)
display.delete(0, tk.END)
print(num_operator)
# List의 index가 2개 이상이 되면 계산 > ex :[1+, 2=] 가 되었을 때
if len(num_operator)>=2:
# 처음 연산자 ['+', '-', '/', '*']
operator = num_operator[0][-1]
try:
first_num = int(num_operator[0].split(operator)[0])
except:
first_num = float(num_operator[0].split(operator)[0])
# 두번 째 연산자가 등호일 때 결과값 출력, 아닐 때 중첩 계산
if num_operator[1][-1] == '=':
result = calculate(operator,first_num,int(num_operator[1].split("=")[0]))
display.insert(tk.END, result)
num_operator.clear()
else:
for op in operators:
if op == num_operator[1][-1]:
second_num = num_operator[1].split(op)
reset = str(calculate(operator, first_num, int(second_num[0])))
num_operator.clear()
num_operator.append(reset+op)
break
# 연산자에 따라 return하는 함수
def calculate(op, num1, num2):
if op == '+': # plus
return num1 + num2
if op == '-': # minus
return num1 - num2
if op == '/': # div
return num1 / num2
if op == '*': # multi
return num1 * num2
# 버튼 GUI SETTINGS
def gui_settings():
# 버튼 크기 설정
height = 2
width = 5
# 숫자 버튼
btn_0 = tk.Button(frame_btns, text='0', height=height, width=width, font=font_nums, command=lambda: btn_click(0))
btn_1 = tk.Button(frame_btns, text='1', height=height, width=width, font=font_nums, command=lambda: btn_click(1))
btn_2 = tk.Button(frame_btns, text='2', height=height, width=width, font=font_nums, command=lambda: btn_click(2))
btn_3 = tk.Button(frame_btns, text='3', height=height, width=width, font=font_nums, command=lambda: btn_click(3))
btn_4 = tk.Button(frame_btns, text='4', height=height, width=width, font=font_nums, command=lambda: btn_click(4))
btn_5 = tk.Button(frame_btns, text='5', height=height ,width=width, font=font_nums, command=lambda: btn_click(5))
btn_6 = tk.Button(frame_btns, text='6', height=height, width=width, font=font_nums, command=lambda: btn_click(6))
btn_7 = tk.Button(frame_btns, text='7', height=height, width=width, font=font_nums, command=lambda: btn_click(7))
btn_8 = tk.Button(frame_btns, text='8', height=height, width=width, font=font_nums, command=lambda: btn_click(8))
btn_9 = tk.Button(frame_btns, text='9', height=height, width=width, font=font_nums, command=lambda: btn_click(9))
btn_0.grid(row=4, column=2)
btn_1.grid(row=3, column=1)
btn_2.grid(row=3, column=2)
btn_3.grid(row=3, column=3)
btn_4.grid(row=2, column=1)
btn_5.grid(row=2, column=2)
btn_6.grid(row=2, column=3)
btn_7.grid(row=1, column=1)
btn_8.grid(row=1, column=2)
btn_9.grid(row=1, column=3)
# 연산자, 클리어 버튼
btn_clear = tk.Button(frame_btns, text='C', height=height, width=width, font=font_nums, command=btn_allclear)
btn_plus = tk.Button(frame_btns, text='+', height=height, width=width, font=font_nums, command=lambda: btn_cal("+"))
btn_minus = tk.Button(frame_btns, text='-', height=height, width=width, font=font_nums, command=lambda: btn_cal("-"))
btn_mul = tk.Button(frame_btns, text='X', height=height, width=width, font=font_nums, command=lambda: btn_cal("*"))
btn_equal = tk.Button(frame_btns, text='=', height=height, width=width, font=font_nums, command=lambda: btn_cal("="))
btn_div = tk.Button(frame_btns, text='/', height=height, width=width, font=font_nums, command=lambda: btn_cal("/"))
btn_plus.grid(row=4, column=4)
btn_minus.grid(row=3, column=4)
btn_mul.grid(row=2, column=4)
btn_div.grid(row=1, column=4)
btn_equal.grid(row=4, column=3)
btn_clear.grid(row=4, column=1)
gui_settings()
root.mainloop()
실행(Run) 방법:
- 우측 상단 ▶ 버튼
- 실행 : Shift + F10
- 선택 실행 : Alt + Shift + F10
python3.9 | camp-lee@naver.com