github : https://github.com/DHL68/github-DHL68/tree/main/22_04_07_calculator
GUI ๊ณ์ฐ๊ธฐ ๋ง๋ค๊ธฐ ๊ฐ์ ๋ด์ฉ
import tkinter as tk
# ๋ช
๋ น์ด ๋ณ์
operator = {'+':1, '-':2, '/':3,
'*':4, 'C':5, '=':6}
disValue = 0 # ๊ฒฐ๊ณผ๊ฐ ๋ณ์ / ์ ์
stoValue = 0 # ์ ์ฅ๋ ๊ฐ
opPre = 0 # ์ด์ ๋ช
๋ น์ด
# ์ซ์ ํด๋ฆญ
def number_click(value):
# print('์ซ์', value)
global disValue
disValue = (disValue * 10) + value
str_value.set(disValue)
# ๋ฆฌ์
def clear():
global disValue, stoValue, opPre
stoValue = 0
opPre = 0
disValue = 0
str_value.set(disValue)
# ํด๋น ๋ช
๋ น ์กฐ๊ฑด
def operator_click(value):
# print('๋ช
๋ น', value)
global disValue, operator, stoValue, opPre
op = operator[value]
if op == 5: # C
clear()
elif disValue == 0:
opPre = 0
elif opPre == 0:
opPre = op
stoValue = disValue
disValue = 0
str_value.set(disValue)
elif op == 6: # =
if opPre == 1:
disValue = stoValue + disValue
if opPre == 2:
disValue = stoValue - disValue
if opPre == 3:
disValue = stoValue / disValue
if opPre == 4:
disValue = stoValue * disValue
str_value.set(str(disValue))
disValue = 0
stoValue = 0
opPre = 0
else:
clear()
# ๋ฒํผ
def button_click(value):
# print(value)
try:
value = int(value)
number_click(value)
except:
operator_click(value)
# ๊ณ์ฐ๊ธฐ ํผ
win = tk.Tk() # ํด๋์ค ์์ฑ
win.title('๊ณ์ฐ๊ธฐ') # ํ์ดํ ์
๋ ฅ
str_value = tk.StringVar()
str_value.set(str(disValue)) # disValue์ ์ ์๋ฅผ str์ ํตํด ๋ฌธ์์ด๋ก ๋ณํ / .set ์ผ๋ก str_value ์ ์
๋ ฅ
dis = tk.Entry(win, textvariable = str_value, justify = 'right', bg = 'white', fg = 'red') # [๊ณ์ฐ๊ธฐ ์
๋ ฅ ํ์ ์์ญ] textvariable ๊ฐ์ ์๋์ผ๋ก ๊ฐฑ์ / justify : ๋ฐฐ์น
dis.grid(column = 0, row = 0, columnspan = 4, ipadx = 80, ipady = 30) # columnspan : colum์ span ์์น ์กฐ์ / ipad x,y input ์ฐฝ์ ํฌ๊ธฐ ์กฐ์
calItem = [['1', '2', '3', '4'],
['5', '6', '7', '8'],
['9', '0', '+', '-'],
['/', '*', 'C', '=']]
for i, items in enumerate(calItem):
for k, item in enumerate(items):
try:
color = int(item) # ์ ์ ์๋ฌ๋ฅผ ์ด์ฉํด์ ์ ์์ผ ๊ฒฝ์ฐ ๊ฒ์์, ์๋ฌ๊ฐ ๋ ๊ฒฝ์ฐ ์ด๋ก์
color = 'black'
except:
color = 'green'
# [๊ณ์ฐ๊ธฐ ์ซ์ ๋ฒํผ ์
๋ ฅ ์์ญ]
bt = tk.Button( # ๋ณ์ ์ ์ธ
win,
text = item, # item ์ ์ธ
width = 10, # ๊ฐ๋ก
height = 5, # ์ธ๋ก
bg = color, # ๋ฐฐ๊ฒฝ์
fg = 'white', # ๊ธ์์
command = lambda cmd = item: button_click(cmd) # item ์ cmd์ ๋ฐ์ ๋ฒํผ ํด๋ฆญ ์ cmd์ ๋ฒํผ ๊ธฐ๋ฅ์ ์
๋ ฅ
)
bt.grid(column = k, row = i + 1) # ๋ฐ๋ณต๊ตฌ๋ฌธ์ ํตํด ๋ฆฌ์คํธ์ ์์๋ฅผ ๋ฐ๋ณต ํฉ์ฐํ์ฌ ์์น ์ง์
win.mainloop() # ๊ณ์ฐ๊ธฐ ๋ชจ๋ ์คํ
์ถ์ฒ : https://youtu.be/rqif36EDSOI