Strength & Honor


계산기 만들기 (2)


계산기에 숫자와 결과를 나타내는 창은 아래와 같다. 이 창의 값을 저장할 변수를 textvariable 속성으로 entry_value 라는 이름으로 설정한다.

여기서 columnspan 을 3 으로 지정한 이유는, 다른 버튼들은 크기와 버튼간의 간격이 동일하다. 허나 이 창은 크기가 전혀 다른 창이다. 이에 column 의 위치를 지정하지 않고 마치 html 의 span 명령처럼 columnspan 으로 처리한다.

여기서 3 이상의 숫자로 지정해야 한다. 3 이라는 숫자는 왼쪽에서 4번째 열이라는 말이다. 나머지 버튼들은 현재 4 x 4 배치이므로

즉 3 보다 작은 숫자를 입력하면 나머지 버튼들의 간격이 넓어진다.

            
  entry_value = StringVar(root, value='')

  number_entry = ttk.Entry(root, textvariable = entry_value, width=35)
  number_entry.grid(row=0, columnspan=3) 
            

그럼 나머지 버튼들을 만들어 보자. 아래 소스를 앞에서 언급한 "숫자 버튼의 위치" 라는 곳에 넣는다.

command = lambda 라는 명령을 사용해서 버튼이 눌렸을때 해당 숫자를 각 버튼에 할당하라는 명령이다. 버튼의 위치는 row 즉 행, column 즉 열에 할당 해 주면 된다.

이렇게 0 부터 8까지 동일한 명령을 사용해서 입력하면 된다.

            
  button7 = ttk.Button(root, text="7", command = lambda:button_pressed('7'))
  button7.grid(row=1, column=0)
  button8 = ttk.Button(root, text="8", command = lambda:button_pressed('8'))
  button8.grid(row=1, column=1)
  button9 = ttk.Button(root, text="9", command = lambda:button_pressed('9'))
  button9.grid(row=1, column=2)
            

4칙 연산을 위한 버튼들은 아래와 같이 입력 해 보자. 4칙 연산을 위해서는 button_pressed 앞에 math 라는 항목을 더 넣어서 입력 해 주면 된다.

              
  button_div = ttk.Button(root, text="/", command = lambda:math_button_pressed('/'))
  button_div.grid(row=1, column=3)
    
  button_mult = ttk.Button(root, text="*", command = lambda:math_button_pressed('*'))
  button_mult.grid(row=2, column=3)
    
  button_add = ttk.Button(root, text="+", command = lambda:math_button_pressed('+'))
  button_add.grid(row=3, column=3)

  button_sub = ttk.Button(root, text="-", command = lambda:math_button_pressed('-'))  
  button_sub.grid(row=4, column=3)
            

마지막으로 "AC, 0, =" 버튼들을 만들어 보자. AC 와 0 버튼은 일반 숫자 버튼과 동일한 명령으로 입력하면 된다. " = " 버튼은 단순히 생각해 보면 math 라는 항목을 이용할 것 같은데 단순 출력하는 역할이므로 equal_button_pressed 라고 입력하는 것 같다.

              
  button_ac = ttk.Button(root, text="AC", command = lambda:button_pressed('AC')) 
  button_ac.grid(row=4, column=0)
  button0 = ttk.Button(root, text="0", command = lambda:button_pressed('0'))
  button0.grid(row=4, column=1)
  button_equal = ttk.Button(root, text="=", command = lambda:equal_button_pressed())  
  button_equal.grid(row=4, column=2)