本文實例為大家分享了python計算器的具體代碼,供大家參考,具體內容如下
主要用到的工具是Python中的Tkinter庫
比較簡單
直接上圖形界面和代碼
引用Tkinter庫
from tkinter import *
建立主窗口對象
window=Tk() #設置窗口對象window.title('counting machine')window.geometry("350x280")window['bg']='red'
建立標簽框以及標簽(將運算字符串顯示在上面)
frame=LabelFrame(window,bg='yellow',width=350,height=50)frame.pack()frame.place(x=0,y=0)label=Label(frame,text="1+1=2",height=3,width=50,bg='yellow')label.pack() #顯示框
設置全局變量字符串s,按一個按鈕,將按鈕對應的運算符加到這個字符串s中,最后利用eval函數進行計算。
global ss=""
按鈕0-9以及小數點的實現(大致思路都是一樣的)
#按鈕.def figure_dot(): global s s=s+"." label.config(text=s)btn0=Button(window,text=".",width=4,command=figure_dot,bg='yellow')btn0.place(x=150,y=220) #按鈕.#按鈕0def figure_0(): global s s=s+"0" label.config(text=s)btn0=Button(window,text="0",width=4,command=figure_0,bg='yellow')btn0.place(x=80,y=220) #按鈕0#按鈕1def figure_1(): global s s=s+"1" label.config(text=s)btn1=Button(window,text="1",width=4,command=figure_1,bg='yellow')btn1.place(x=10,y=80) #按鈕1#按鈕2def figure_2(): global s s=s+"2" label.config(text=s)btn2=Button(window,text="2",width=4,command=figure_2,bg='yellow')btn2.place(x=80,y=80)#按鈕2#按鈕3def figure_3(): global s s=s+"3" label.config(text=s)btn3=Button(window,text="3",width=4,command=figure_3,bg='yellow')btn3.place(x=150,y=80)#按鈕3#按鈕4def figure_4(): global s s=s+"4" label.config(text=s)btn4=Button(window,text="4",width=4,command=figure_4,bg='yellow')btn4.place(x=10,y=130)#按鈕4#按鈕5def figure_5(): global s s=s+"5" label.config(text=s)btn5=Button(window,text="5",width=4,command=figure_5,bg='yellow')btn5.place(x=80,y=130)#按鈕5#按鈕6def figure_6(): global s s=s+"6" label.config(text=s)btn6=Button(window,text="6",width=4,command=figure_6,bg='yellow')btn6.place(x=150,y=130)#按鈕6#按鈕7def figure_7(): global s s=s+"7" label.config(text=s)btn7=Button(window,text="7",width=4,command=figure_7,bg='yellow')btn7.place(x=10,y=180)#按鈕7#按鈕8def figure_8(): global s s=s+"8" label.config(text=s)btn8=Button(window,text="8",width=4,command=figure_8,bg='yellow')btn8.place(x=80,y=180)#按鈕8#按鈕9def figure_9(): global s s=s+"9" label.config(text=s)btn9=Button(window,text="9",width=4,command=figure_9,bg='yellow')btn9.place(x=150,y=180)#按鈕9
運算符號的實現(±*/)
#加法按鈕def figure_addition(): global s s=s+"+" label.config(text=s)btn_add=Button(window,text="+",width=4,command=figure_addition,bg='yellow')btn_add.place(x=220,y=80)#加法按鈕#減法按鈕def figure_subtraction(): global s s=s+"-" label.config(text=s)btn_sub=Button(window,text="-",width=4,command=figure_subtraction,bg='yellow')btn_sub.place(x=220,y=130)#減法按鈕#乘法按鈕def figure_multiplication(): global s s=s+"*" label.config(text=s)btn_multi=Button(window,text="*",width=4,command=figure_multiplication,bg='yellow')btn_multi.place(x=290,y=80)#乘法按鈕#除法按鈕def figure_division(): global s s=s+"/" label.config(text=s)btn_divi=Button(window,text="/",width=4,command=figure_division,bg='yellow')btn_divi.place(x=290,y=130)#除法按鈕
新聞熱點
疑難解答