1. 程式人生 > >基於Tkinter用50行Python程式碼實現簡易計算器

基於Tkinter用50行Python程式碼實現簡易計算器

Tkinter一般是python自帶的,所以程式碼不需要其他元件,本程式是在python2.7版本實現的。 

 主要涉及了tkinter的使用,函式定義和呼叫,匿名函式的使用,類成員函式定義等python基礎知識,適合新手學習。

 程式碼如下:

from Tkinter import *

#建立橫條型框架
def frame(root, side):
    w = Frame(root)
    w.pack(side = side, expand = YES, fill = BOTH)
    return w
#建立按鈕
def button(root, side, text, command = None):
    w = Button(root, text = text, command = command)
    w.pack(side = side, expand = YES, fill = BOTH)
    return w
#繼承了Frame類,初始化程式介面的佈局
class Calculator(Frame):
    def __init__(self):
        
        Frame.__init__(self)
        
        self.pack(expand = YES, fill = BOTH)
        self.master.title('Simple Calculater')
        
        display = StringVar()
        #新增輸入框
        Entry(self, relief = SUNKEN,
              textvariable = display).pack(side = TOP, expand = YES,
                                           fill = BOTH)
		#新增橫條型框架以及裡面的按鈕
        for key in('123', '456', '789', '-0.'):
            keyF = frame(self, TOP)
            for char in key:
                button(keyF, LEFT, char, lambda w = display, c = char:w.set(w.get() + c))
		#新增操作符按鈕
        opsF = frame(self, TOP)
        for char in '+-*/=':
            if char == '=':
                btn = button(opsF, LEFT, char)
                btn.bind('<ButtonRelease - 1>', lambda e, s = self, w = display:s.calc(w), '+')

            else:
                btn = button(opsF, LEFT, char, lambda w = display, s = '%s' %char:w.set(w.get() + s))
		#新增清除按鈕
        clearF = frame(self, BOTTOM)
        button(clearF, LEFT, 'clear', lambda w = display:w.set(''))

	#呼叫eval函式計算表示式的值
    def calc(self, display):
        try:
            display.set(eval(display.get()))
        except:
            display.set("ERROR")
#程式的入口
if __name__ == '__main__':
    print('ok')
    Calculator().mainloop()
        
實現效果如下圖: