계산기 만들기

 

 

import tkinter as tk

operation = ''   #연산자 저장 변수
temp_number = 0   #이전값 저장 변수

def button(val):
    if val == 'C':
        number.delete(0, 'end')
    else:
        number.insert('end', val)
        print(val)
    

def cal(val):
    global operation
    global temp_number
    if number.get() != '':
        operation = val
        temp_number = int(number.get())
        number.delete(0, 'end')
        print(temp_number, operation) 
    
def equl():
    global operation
    global temp_number
    if operation != '' and number.get() !='':
        num = int(number.get())
        if operation == '+':
            solution = temp_number+num
        elif operation == '-':
            solution = temp_number - num
        elif operation == '*':
            solution = temp_number * num
        else:
            solution = temp_number/num
            
        number.delete(0,'end')
        number.insert(0,solution)            
        print(temp_number,operation,num,'=',solution) 
        operation =''
        temp_number = 0
    
    
win = tk.Tk()
win.title('Calculator')
win.geometry('300x400+100+100')
win.resizable(False, False)

label = tk.Label(win, height=4)
label.grid(row=0, column=0)

entry_value = StringVar(win, value='')

number = ttk.Entry(win, textvariable = entry_value, width=20)  #숫자 및 결과 표시창
number.grid(row=0, columnspan=3)

b1 = tk.Button(text='1', width=7, height=4, command=lambda:button('1'))
b1.grid(row=1, column=0)
b2 = tk.Button(text='2', width=7, height=4, command=lambda:button('2'))
b2.grid(row=1, column=1)
b3 = tk.Button(text='3', width=7, height=4, command=lambda:button('3'))
b3.grid(row=1, column=2)
b4 = tk.Button(text='+', width=7, height=4, command=lambda:cal('+'))
b4.grid(row=1, column=3)

b5 = tk.Button(text='4', width=7, height=4, command=lambda:button('4'))
b5.grid(row=2, column=0)
b6 = tk.Button(text='5', width=7, height=4, command=lambda:button('5'))
b6.grid(row=2, column=1)
b7 = tk.Button(text='6', width=7, height=4, command=lambda:button('6'))
b7.grid(row=2, column=2)
b8 = tk.Button(text='-', width=7, height=4, command=lambda:cal('-'))
b8.grid(row=2, column=3)

b9 = tk.Button(text='7', width=7, height=4, command=lambda:button('7'))
b9.grid(row=3, column=0)
b10 = tk.Button(text='8', width=7, height=4, command=lambda:button('8'))
b10.grid(row=3, column=1)
b11 = tk.Button(text='9', width=7, height=4, command=lambda:button('9'))
b11.grid(row=3, column=2)
b12 = tk.Button(text='*', width=7, height=4, command=lambda:cal('*'))
b12.grid(row=3, column=3)

b13 = tk.Button(text='0', width=7, height=4, command=lambda:button('0'))
b13.grid(row=4, column=0)
b14 = tk.Button(text='C', width=7, height=4, command=lambda:f1('C'))
b14.grid(row=4, column=1)
b15 = tk.Button(text='=', width=7, height=4, command=lambda:equl())
b15.grid(row=4, column=2)
b16 = tk.Button(text='/', width=7, height=4, command=lambda:cal('/'))
b16.grid(row=4, column=3)
    
win.mainloop()

아직 계산 오류(소숫점 등)를 고려하지 않은 상태이다.

 

앗, eval 함수를 쓰면 cal, equl 함수 없이도 되는구나..

def f1(val):
    s = label.cget('text')
    s += val #s:12
    label.config(text=s)#config():위젯 속성의 값을 읽거나 설정
    
def calc():
    s = label.cget('text') #s:'5-1+6*2'
    print(s)
    res = eval(s)
    label.config(text=str(res))
    
def clear():
    label.config(text='')
    
win = tk.Tk()#Tk객체 생성=>기본 윈도우와 ui api를 제공하는 객체
win.title('window title')
win.geometry('300x400+100+100')
win.resizable(False, False)

#위젯 생성 및 배치
label = tk.Label(win, height=4)
label.grid(row=0, column=0)

b1 = tk.Button(text='1', width=7, height=4, command=lambda:f1('1'))
b1.grid(row=1, column=0)
b2 = tk.Button(text='2', width=7, height=4, command=lambda:f1('2'))
b2.grid(row=1, column=1)
b3 = tk.Button(text='3', width=7, height=4, command=lambda:f1('3'))
b3.grid(row=1, column=2)
b4 = tk.Button(text='+', width=7, height=4, command=lambda:f1('+'))
b4.grid(row=1, column=3)
b5 = tk.Button(text='4', width=7, height=4, command=lambda:f1('4'))
b5.grid(row=2, column=0)
b6 = tk.Button(text='5', width=7, height=4, command=lambda:f1('5'))
b6.grid(row=2, column=1)
b7 = tk.Button(text='6', width=7, height=4, command=lambda:f1('6'))
b7.grid(row=2, column=2)
b8 = tk.Button(text='-', width=7, height=4, command=lambda:f1('-'))
b8.grid(row=2, column=3)
b9 = tk.Button(text='7', width=7, height=4, command=lambda:f1('7'))
b9.grid(row=3, column=0)
b10 = tk.Button(text='8', width=7, height=4, command=lambda:f1('8'))
b10.grid(row=3, column=1)
b11 = tk.Button(text='9', width=7, height=4, command=lambda:f1('9'))
b11.grid(row=3, column=2)
b12 = tk.Button(text='*', width=7, height=4, command=lambda:f1('*'))
b12.grid(row=3, column=3)
b13 = tk.Button(text='0', width=7, height=4, command=lambda:f1('0'))
b13.grid(row=4, column=0)
b14 = tk.Button(text='C', width=7, height=4, command=clear)
b14.grid(row=4, column=1)
b15 = tk.Button(text='=', width=7, height=4, command=calc)
b15.grid(row=4, column=2)
b16 = tk.Button(text='/', width=7, height=4, command=lambda:f1('/'))
b16.grid(row=4, column=3)
    
win.mainloop()

 

 

심지어 버튼 구현 노가다 없이 for문으로도 가넝...

 

def f1(val):
    s = label.cget('text')
    s += val
    label.config(text=s)   #config():위젯 속성의 값을 읽거나 설정

def calc():
    s = label.cget('text')
    print(s)
    res = eval(s)    #eval 함수: 자동으로 계산해주는 함수
    label.config(text=str(res))
    
def clear():
    label.config(text='')
    
win = tk.Tk()
win.title('window title')
win.geometry('300x400+100+100')
win.resizable(False, False)
   
label = tk.Label(win, height=4)
label.grid(row=0, column=0)

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

    
for i in range(0, 4):
    for j in range(0, 4):
        num = nums[i][j]
        if num =='C':
            b = tk.Button(text=num, width=7, height=4, command=clear)
        elif num == '=':
            b = tk.Button(text=num, width=7, height=4, command=calc)
        else:
            b = tk.Button(text=num, width=7, height=4, command=lambda val=num :f1(val))
        b.grid(row=(i+1), column=j)
        
        
win.mainloop()

 

'파이썬II' 카테고리의 다른 글

파이썬II #Web Data Read  (0) 2021.07.02
파이썬II # 공공데이터 분석(1)  (0) 2021.07.01
파이썬II #파일 open 후 데이터 추출하기  (0) 2021.06.30
<!doctype himl> -- 문서종류 지정:html
<html>
  <head>
    <title> asdf </title>
  </head>
  <body>
    <div id='d1' class='c1'> 웹페이지에 들어갈 내용 </div>
    <div id='d2' class='c1'> 웹페이지에 들어갈 내용 </div>
    <div id='d3' class='c2'> 웹페이지에 들어갈 내용 </div>
    <a href=">adsf</a>
    <h1>adf</h1>
  </body?
</html>

 

DOM(Document Object Model)

         root --- 문서

               ㅣ

             html

                l

     head --------body

       l--------------l

     title            div-----p

 

 

 

ajax(비동기 javascript and xml)

 

html 페이지

공공데이터 표현 방법

json(javascript object notation)

  (오늘의 날씨 같은 거, 실시간으로 바뀌는 정보들)

  객체는 {}

  배열 []

xml (요즘엔 사용 잘 안해)

  디스크립터 : 시스템(컨테이너)에 설명하는 파일, xml로 표현

  공공데이터표현

 

{'name':'aaa', 'tet':'1111', 'addr':'대한민국'}

[{'name':'aaa', 'tet':'1111', 'addr':'대한민국'},

{'name':'aaa', 'tet':'1111', 'addr':'대한민국'),

{'name':'aaa', 'tet':'1111', 'addr':'대한민국')]

 

<persons>
  <person>
     <name>aaa</name>
     <tet>111</tel>
     <addr>qwerqw</addr>
  </person>
  
  <person>
     <name>bbb</name>
     <tet>222</tel>
     <addr>asdfsdf</addr>
  </person>
</persons>

 

'파이썬II' 카테고리의 다른 글

tkinter #계산기 만들기  (0) 2021.07.08
파이썬II # 공공데이터 분석(1)  (0) 2021.07.01
파이썬II #파일 open 후 데이터 추출하기  (0) 2021.06.30
import numpy as np
import pandas as pd

data=pd.read_csv('d.csv', encoding='euc-kr')
data

 

 

a=data[data.columns].loc[:11]
a

 

a = data[['월','사고건수','사망자수','중상자수','경상자수','부상신고자수']].loc[:11]
a

 

 

val = a.values
title = data['가해자연령층'][0]
cols = [[title,title,title,title,title,title],data.columns[1:]]
x = pd.DataFrame(val, columns=cols)
x

 

 

#배열명[컬럼명]
#배열명.loc[인덱스명]
#a.data[data.cols = [data.columns[1:]].loc[:11]  #원하는 요소만 추출

tabs = []
idx = ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월']
cnt = len(data)//12     # / 1개면  실수로 계산, // 2개면 정수로 계산
for i in range(0, cnt):
    y= i*12
    title = data['가해자연령층'][y]
    vals = data[data.columns[2:]].loc[y:y+11]
    cols = [[title,title,title,title,title],data.columns[2:]]
    x = pd.DataFrame(vals.values, columns = cols, index=idx)
    tabs.append(x)
    
tabs

 

 

 

 

res = tabs[0]
res=tabs[0]
for i in range(1, len(tabs)):
    res = res.join(tabs[i])
    
res

 

#연령별 최대 사고 발생월과 사고수

for i in tabs:
    #m = i['20세이하',사고건수'].max()   #하드코드 불가능
    #x = i['20세이하','사고건수'].argmax()
    m = i[i.columns[0]].max()
    x = i[i.columns[0]].argmax()
    print(i.columns[0][0],'의 최대 사고건수:',m, ' / 발생 월:',idx[x] )

 

 

#연령별 12개월의 사고발생 총건, 총 사망자수

for i in tabs:
    s = i[i.columns[0]].sum()
    d = i[i.columns[1]].sum()
    print(i.columns[0][0],'의 사고발생 총 건:',s, ' / 총 사망자수:',d) 

 

#연령별 12개월 사고 발생 평균 값

for i in tabs:
    m = i[i.columns[0]].mean()
    print(i.columns[0][0],'의 사고 발생 평균:',m) 

'파이썬II' 카테고리의 다른 글

tkinter #계산기 만들기  (0) 2021.07.08
파이썬II #Web Data Read  (0) 2021.07.02
파이썬II #파일 open 후 데이터 추출하기  (0) 2021.06.30

Q.

파일명: a.txt

내용

이름,국어,영어,수학
aaa,43,54,65
bbb,7,67,87
ccc,54,65,76

 

a.txt 파일을 오픈하여 성적추출하기.

 

import numpy as np

#파일 내용을 한 줄 씩 읽음

f = open('./stu_data.txt', 'r')
datas = []
while True:
    s = f.readline()    # s: '1, aaa, 43, 65, 78 \n'
    if s == '':
        break
    s = s.split('\n')[0]   #엔터를 잘라냄 -> s: '1, aaa, 43, 465, 78'
    stu = s.split(',')    # stu: ['1', 'aaa', '43', '65', '78']
    for i in range(0, 2):
        stu.append(0)
    datas.append(stu)
f.close()

datas

여기에서 s.split('\n')[0]는 \n을 기준으로 두 조각(예를들어, aaa,43,54,65\n 이 있다면 \n을 기준으로 앞과 뒤를 나누게 되어 두조각이 됌)에서 0번째 방에 해당하는 앞 조각만 사용하겠다는 뜻이다.

 

# datas리스트를 numpy 배열로 변환
arr = np.array(datas)
arr

 

 

# 각 학생의 이름만 추출
names = arr[:,0]
names

 

 

# 각 학생의 점수 추출
score = arr[:, 1:]
score

 

 

#점수 배열 요소 타입을 float으로 변경
x = arr[:, 1:]
score = x.astype(np.float32
score

 

 

#모든 줄의 총점, 평균 계산
'''
for i in score:
    k = i[1:4]      # k: [국,영,수]
    sum1 = k.sum()
    i[4]=sum1
    i[5]=sum1/3
'''

score[:,4] = score[:,1:4].sum(axis=1)   #axis=1 : 가로줄
score[:,5] = score[:,4]/3

score
print('각 학생의 총점,평균')
for i in range(0, 5):
    print(names[i], end='\t')
    print(score[i])

 

 

#학생들의 국어총점, 영어총점, 수학총점
'''
kor = score[:,1].sum(axis=0)
eng = score[:.2].sum(axis=0)
math = score[:,3].sum(axis=0)
'''
sums = score.sum(axis=0)    #axis=0 : 세로줄

print('국어총점:', sums[1])
print('영어총점:', sums[2])
print('수학총점:', sums[3])
print('전체총점:', sums[4])
print('전체평균합:', sums[5])

'파이썬II' 카테고리의 다른 글

tkinter #계산기 만들기  (0) 2021.07.08
파이썬II #Web Data Read  (0) 2021.07.02
파이썬II # 공공데이터 분석(1)  (0) 2021.07.01

+ Recent posts