基於tkinter的簡易計算器
阿新 • • 發佈:2021-12-12
tkinter 介紹
tkinter是python自帶的GUI庫,是對圖形庫TK的封裝
tkinter是一個跨平臺的GUI庫,開發的程式可以在win,linux或者mac下執行
按鈕元件:
Button 按鈕元件
RadioButton 單選框元件
CheckButton 選擇按鈕元件
Listbox 列表框元件
文字輸入框元件:
Entry 單行文字框元件
Text 多行文字框元件
標籤元件:
Label 標籤元件,可以顯示圖片和文字
Message 標籤元件,可以根據內容將文字換行
選單元件:
Menu 選單元件
MenuButton 選單按鈕元件,可以使用Menu替代
其他元件:
Canvas 畫布元件
Frame 框架元件
Toplevel 建立子視窗容器元件
........
更多詳見https://blog.csdn.net/qq_40223983/article/details/96093396?utm_source=app&app_version=4.20.0
簡易計算器的實現:
1 from tkinter import * 2 def calculate(): 3 result=eval(equ.get()) 4 equ.set(equ.get()+'=\n'+str(result)) 5 def show(buttonString):6 content=equ.get() 7 if content=='0': 8 content="" 9 equ.set(content+buttonString) 10 root = Tk() 11 root.title('計算器') 12 equ = StringVar() 13 equ.set('0') 14 label = Label(root, width=25, height=2, relief=RAISED, anchor=SE, 15 textvariable=equ) 16 label.grid(row=0, column=0, columnspan=4, padx=5, pady=5)17 clearButton=Button(root, text='C', fg='blue', width=5, command=lambda:equ.set('0')) 18 clearButton.grid(row=1, column=0) 19 Button(root, text='DEL', width=5, command=lambda:equ.set(str(equ.get()[:-1]))).grid(row=1,column=1) 20 Button(root, text="%", width=5,command=lambda:show('%')).grid(row=1, column=2) 21 Button(root, text="/", width=5,command=lambda:show('/')).grid(row=1, column=3) 22 Button(root, text="7", width=5,command=lambda:show('7')).grid(row=2, column=0) 23 Button(root, text="8", width=5,command=lambda:show('8')).grid(row=2, column=1) 24 Button(root, text="9", width=5,command=lambda:show('9')).grid(row=2, column=2) 25 Button(root, text="*", width=5,command=lambda:show('*')).grid(row=2, column=3) 26 Button(root, text="4", width=5,command=lambda:show('4')).grid(row=3, column=0) 27 Button(root, text="5", width=5,command=lambda:show('5')).grid(row=3, column=1) 28 Button(root, text="6", width=5,command=lambda:show('6')).grid(row=3, column=2) 29 Button(root, text="-", width=5,command=lambda:show('-')).grid(row=3, column=3) 30 Button(root, text="1", width=5,command=lambda:show('1')).grid(row=4, column=0) 31 Button(root, text="2", width=5,command=lambda:show('2')).grid(row=4, column=1) 32 Button(root, text="3", width=5,command=lambda:show('3')).grid(row=4, column=2) 33 Button(root, text="+", width=5,command=lambda:show('+')).grid(row=4, column=3) 34 Button(root, text="0", width=5,command=lambda:show('0')).grid(row=5, column=0,columnspan=2) 35 Button(root, text=".", width=5,command=lambda:show('.')).grid(row=5, column=2) 36 Button(root, text="=", width=5,command=lambda:calculate()).grid(row=5, column=3) 37 root.mainloop()