tft每日頭條

 > 科技

 > python怎麼用代碼寫一個計算器

python怎麼用代碼寫一個計算器

科技 更新时间:2024-11-27 16:52:56


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)1

有點長,适合收藏,慢慢閱讀和分析不同代碼的編寫和改進。

1.第一例37行代碼

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,bg='pink', font=10,command = command) w.pack(side = side, expand = YES, fill = BOTH) return w class Calculator(Frame): #繼承了Frame類,初始化程序界面的布局 def __init__(self): Frame.__init__(self) self.pack(expand = YES, fill = BOTH) self.master.title('簡易計算器1') #窗口标題 self.master.geometry("1020x800 500 0") #窗口大小和位置 display = StringVar() Entry(self, relief = SUNKEN,font=15,fg='red',bg='black',just='right',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 (' ','-','*','/','='): #倒數第二行,還可以寫成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('')) #清除鍵内不能設置為0,否則出問題 def calc(self, display): #調用eval函數計算表達式的值 try: display.set(eval(display.get())) except: display.set("ERROR") if __name__ == '__main__': Calculator().mainloop()

圖1


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)2

2.第二例41行代碼

from tkinter import * #模塊導出 root=Tk() root.title("簡易計算器2") root.geometry("1020x800 500 0") #代表500,0=x,y,水平線是0,頂上線,水平移動500,水平線向右移動500 reset=True def buttonCallBack(event): global label global reset num=event.widget['text'] if num=='C': #如何按C,清除鍵,就是歸零 label['text']="0" return if num=='←': #如何按C,清除鍵,就是歸零 label['text']=label['text'][0:-1] return if num in "=": label['text']=str(eval(label['text'])) reset=True return s=label['text'] if s=='0' or reset==True: s=" " #注意要有空格,否則0.1 0.2,則0.1的0顯示不出來 reset=False label['text']=s num label=Label(root,text="0",background="black",font = ('微軟雅黑',30),fg='red',width=18,height=1,anchor="se") label.grid(row=1,columnspan=4,sticky=W) showText="123 456-789*0.%/" #這個按鈕的内容和順序,可以調整的 for i in range(4): #一行4個按鈕 for j in range(4): b=Button(root,text=showText[i*4 j],font=4,bg='pink',width=10,height=2) b.grid(row=i 2,column=j) b.bind("<Button-1>",buttonCallBack) showText="C←" for i in range(2): b=Button(root,text=showText[i],width=10,bg='pink',height=2,font=4) b.grid(row=6,column=i) b.bind("<Button-1>",buttonCallBack) b=Button(root,text="=",bg='orange',height=2,font=4) b.grid(row=6,column=2,columnspan=2,sticky="we") b.bind("<Button-1>",buttonCallBack) root.mainloop()

圖2


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)3

3.第三例44行代碼

from tkinter import * root = Tk() root.title("簡易計算器3") root.geometry("1020x800 500 0") #代表500,0=x,y,水平線是0,頂上線,水平移動500,水平線向右移動500 class App: def __init__(self, master): self.master = master self.initWidgets() self.hi = '0' def initWidgets(self): self.show = Label(relief=SUNKEN, font=('Verdana', 24),width=25, bg='black',fg='red', anchor=E) self.show.pack(side=TOP, pady=10) p = Frame(self.master) p.pack(side=TOP) names = (" ", "1" , "2" , "3" , "%" ,"-", "4" , "5" , "6" , "**" , "*", "7" , "8" , "9", "←", "/" , "." , "0" , "clear", "=") #定義元組,非常好,代碼簡潔,順序就是按鈕的順序 for i in range(len(names)): b = Button(p, text=names[i], bg='pink',font=('Verdana', 20), width=5) # 創建Button,将Button放入p組件中 b.grid(row=i // 5, column=i % 5) b.bind('<Button-1>', self.click) # 為鼠标左鍵的單擊事件綁定事件處理方法 if b['text'] == 'clear': b.bind('<Button-1>', self.clean) # 為鼠标左鍵的雙擊事件綁定事件處理方法 if b['text'] == '←': b.bind('<Button-1>', self.back) self.i = 0 # 定義一個記錄輸入數字次數的變量 def click(self, event): if(event.widget['text'] in ('0', '1', '2', '3','4', '5', '6', '7', '8', '9', '.')): # 如果用戶單擊的是數字鍵或點号 if self.i == 0 : # 判斷self.i是否為0,0的話清空show['text']的值 self.show['text'] = '' self.show['text'] = self.show['text'] event.widget['text'] self.i = self.i 1 elif(event.widget['text'] in (' ', '-', '*', '/', '%', '**')): # 如果用戶單擊了運算符 self.show['text'] = self.show['text'] event.widget['text'] # 把輸入的數字與輸入的字符相結合,組成一個數學運算式 elif(event.widget['text'] == '=' and self.show['text'] is not None): self.hi = self.show['text'] # 賦值給self.hi self.show['text'] = str(eval(self.hi)) #使用eval函數計算表達式的值 self.hi = '0' self.i = 0 def clean(self, event): # 點擊clear(恢複)按鈕時,程序清空計算結果、将表達式設為0 self.hi = '0' self.show['text'] = '' #歸零 def back(self, event): #←的back的功能定義 self.hi = self.show['text'] self.show['text'] = self.hi[0:-1] App(root) root.mainloop()

圖3


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)4

4.第四例63行代碼

from tkinter import * from functools import partial def GUI(): root=Tk() root.title("簡易計算器4") root.geometry("1020x800 500 0") entry=Entry(root,justify="right",bg='black',fg='red',font=20) entry.grid(row=0,column=0,columnspan=4,sticky=N,padx=5,pady=5) #輸入框,justify="right"表示多行文本的對齊方式是右對齊 myButton=partial(Button,root,bg='pink',padx=10,font=10,pady=3,activebackground='#B3EE3A') b7=myButton(text='7',command=lambda : get_input(entry,'7')) #按鈕第一層 b7.grid(row=1,column=0,sticky=N S E W) #按鈕大小通過sticky=N S E W來填充,變大 b8=myButton(text='8',command=lambda : get_input(entry,'8')) b8.grid(row=1,column=1,sticky=N S E W) b9=myButton(text='9',command=lambda : get_input(entry,'9')) b9.grid(row=1,column=2,sticky=N S E W) b_add=myButton(text=' ',command=lambda : get_input(entry,' ')) b_add.grid(row=1,column=3,sticky=N S E W) b4=myButton(text='4',command=lambda : get_input(entry,'4')) #按鈕第二層 b4.grid(row=2,column=0,sticky=N S E W) b5=myButton(text='5',command=lambda : get_input(entry,'5')) b5.grid(row=2,column=1,sticky=N S E W) b6=myButton(text='6',command=lambda : get_input(entry,'6')) b6.grid(row=2,column=2,sticky=N S E W) b_subtract=myButton(text='-',command=lambda : get_input(entry,'-')) b_subtract.grid(row=2,column=3,sticky=N S E W) b1=myButton(text='1',command=lambda : get_input(entry,'1')) #按鈕第三層 b1.grid(row=3,column=0,sticky=N S E W) b2=myButton(text='2',command=lambda : get_input(entry,'2')) b2.grid(row=3,column=1,sticky=N S E W) b3=myButton(text='3',command=lambda : get_input(entry,'3')) b3.grid(row=3,column=2,sticky=N S E W) b_multiply=myButton(text='*',command=lambda : get_input(entry,'*')) b_multiply.grid(row=3,column=3,sticky=N S E W) b0=myButton(text='0',command=lambda : get_input(entry,'0')) #按鈕第四層 b0.grid(row=4,column=0,sticky=N S E W) b_point=myButton(text='.',command=lambda : get_input(entry,'.')) b_point.grid(row=4,column=1,sticky=N S E W) b_clear=myButton(text='%',command=lambda : get_input(entry,'%')) b_clear.grid(row=4,column=2,columnspan=1,sticky=N S E W) b_divide=myButton(text='/',command=lambda : get_input(entry,'/')) b_divide.grid(row=4,column=3,sticky=N S E W) b_clear=myButton(text='clear',command=lambda : clear(entry)) #按鈕第五層 b_clear.grid(row=5,column=0,columnspan=1,sticky=N S E W) b_back=myButton(text='<-',command=lambda : backspace(entry)) b_back.grid(row=5,column=1,sticky=N S E W) b_equal=myButton(text='=',bg='orange',command=lambda : calculate(entry)) b_equal.grid(row=5,column=2,columnspan=2,sticky=N S E W) root.mainloop()#這個循環在GUI裡 def get_input(entry,argu): entry.insert(END,argu) def backspace(entry):#按鈕"<-"事件處理函數 input_len=len(entry.get()) entry.delete(input_len-1) def clear(entry):#按鈕"clear"事件處理函數 entry.delete(0,END) def calculate(entry):#按鈕"="事件處理函數 input = entry.get() output = str(eval(input.strip())) #eval函數使用起來,代碼就很簡單簡潔 clear(entry) entry.insert(END, output) if __name__ == "__main__": GUI()

圖4


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)5

5.第五例69行代碼

from tkinter import * from functools import partial def get_input(entry, argu): entry.insert(END, argu) def backspace(entry): input_len = len(entry.get()) entry.delete(input_len - 1) def clear(entry): entry.delete(0, END) def calc(entry): input = entry.get() output = str(eval(input.strip())) clear(entry) entry.insert(END, output) def cal(): root = Tk() root.title("簡易計算器5") root.geometry("1020x800 500 0") entry = Entry(root, justify="right",bg='black',fg='red',font=10,width=50) #顯示文本框的設置 entry.grid(row=0, column=0, columnspan=4, sticky=N W S E, padx=5, pady=5)#顯示文本框的大小 button_bg = 'pink' #按鈕的初始背景顔色 button_active_bg = '#E5E35B' #按鈕激活的背景顔色,黃色 myButton = partial(Button, root, bg=button_bg, font=20,padx=10, pady=3, activebackground = button_active_bg) #第一層 b7 = myButton(text='7', command=lambda : get_input(entry, '7')) b7.grid(row=1, column=0, columnspan=1,pady=5,sticky=N S E W) b8 = myButton(text='8', command=lambda : get_input(entry, '8')) b8.grid(row=1, column=1, columnspan=1,pady=5,sticky=N S E W) b9 = myButton(text='9', command=lambda : get_input(entry, '9')) b9.grid(row=1, column=2, columnspan=1,pady=5,sticky=N S E W) b10 = myButton(text=' ', command=lambda : get_input(entry, ' ')) b10.grid(row=1, column=3, columnspan=1,pady=5,sticky=N S E W) #第二層 b4 = myButton(text='4', command=lambda : get_input(entry, '4')) b4.grid(row=2, column=0, columnspan=1,pady=5,sticky=N S E W) b5 = myButton(text='5', command=lambda : get_input(entry, '5')) b5.grid(row=2, column=1, columnspan=1,pady=5,sticky=N S E W) b6 = myButton(text='6', command=lambda : get_input(entry, '6')) b6.grid(row=2, column=2, columnspan=1,pady=5,sticky=N S E W) bj = myButton(text='-', command=lambda : get_input(entry, '-')) bj.grid(row=2, column=3, columnspan=1,pady=5,sticky=N S E W) #第三層 b1 = myButton(text='1', command=lambda : get_input(entry, '1')) b1.grid(row=3, column=0, columnspan=1,pady=5,sticky=N S E W) b2 = myButton(text='2', command=lambda : get_input(entry, '2')) b2.grid(row=3, column=1, columnspan=1,pady=5,sticky=N S E W) b3 = myButton(text='3', command=lambda : get_input(entry, '3')) b3.grid(row=3, column=2, columnspan=1,pady=5,sticky=N S E W) bc = myButton(text='*', command=lambda : get_input(entry, '*')) bc.grid(row=3, column=3, columnspan=1,pady=5,sticky=N S E W) #第四層 b0 = myButton(text='0', command=lambda : get_input(entry, '0')) b0.grid(row=4, column=0, columnspan=1, padx=3, pady=5, sticky=N S E W) bpc = myButton(text='%', command=lambda : get_input(entry, '%')) bpc.grid(row=4, column=1, columnspan=1, padx=3, pady=5, sticky=N S E W) bd = myButton(text='.',command=lambda : get_input(entry, '.')) bd.grid(row=4, column=2, columnspan=1,pady=5,sticky=N S E W) bcf = Button(root, text='/', bg=button_bg, font=20,padx=10, pady=3,command=lambda : get_input(entry, '/')) bcf.grid(row=4, column=3, columnspan=1,pady=5,sticky=N S E W) #第五層 bb = Button(root, text='←', bg=button_bg, font=20,padx=10, pady=3,command=lambda : backspace(entry), activebackground = button_active_bg) bb.grid(row=5, column=0, columnspan=1,pady=5,sticky=N S E W) bcl = Button(root, text='Clear', bg=button_bg, font=20,padx=10, pady=3,command=lambda : clear(entry), activebackground = button_active_bg) bcl.grid(row=5, column=1, columnspan=1,pady=5,sticky=N S E W) bdy = Button(root, text='=', bg='orange', font=20,padx=10, pady=3,command=lambda : calc(entry), activebackground = button_active_bg) bdy.grid(row=5, column=2, columnspan=2, padx=3, pady=5, sticky=N S E W) root.mainloop() if __name__ == '__main__': cal()

圖5


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)6

6.第六例70行代碼

from tkinter import * from tkinter.ttk import * #不支持背景顔色改變 root = Tk() # 開始界面的實現 root.title("簡易計算器6") # 添加标題 root.geometry("1020x800 500 0") #代表500,0=x,y,水平線是0,頂上線,水平移動500,水平線向右移動500 def frame(master): #定義frame的屬性 w = Frame(master) #将共同的屬性作為默認值, 以簡化Frame創建過程 w.pack(side=TOP, expand=YES, fill=BOTH) return w def button(master, text,command): #提取共同的屬性作為默認值, 使Button創建過程簡化 w = Button(master,text=text,command=command,width=6) #比較好,将共同屬性提取,并統一設置,這樣代碼簡潔 w.pack(side=LEFT, expand=YES, fill=BOTH, padx=2, pady=2) return w def back(text): #将text最末的字符删除并返回 if len(text) > 0: return text[:-1] else: return text def calc(text): #用eval方法計算表達式字符串 try: if (sep_flag.get() == 0): return eval(del_sep(text)) else: return add_sep(str(eval(del_sep(text)))) except (SyntaxError, ZeroDivisionError, NameError): return 'Error' def add_sep(text): dot_index = text.find('.') if dot_index > 0: text_head = text[:dot_index] text_tail = text[dot_index:] elif dot_index < 0: text_head = text text_tail = '' else: text_head = '' text_tail = text list_ = [char for char in text_head] length = len(list_) tmp_index = 3 while length - tmp_index > 0: list_.insert(length - tmp_index, ',') tmp_index = 3 list_.extend(text_tail) new_text = '' for char in list_: new_text = char return new_text def del_sep(text): #删除數字串中所有的千位分隔符 return text.replace(',', '') text = StringVar() #定義 text.set('0') #初始化為0 sep_flag = IntVar() sep_flag.set(0) Entry(root,textvariable=text,font=30,just='right').pack(expand=YES, fill=BOTH, padx=2, pady=4) # 創建文本框 style = Style() style.configure('TButton',background='pink',font=10,padding=3) #按鈕字體大小設置,bg不行,需要background才行 for key in ('789 ', '456-', '123*', '0%./','='): #這種方法非常簡潔,值得推薦;# 每行四個, 創建其餘四行按鈕 fsymb = frame(root) for char in key: if char == '=': button(fsymb,char, lambda t=text: t.set(calc(t.get()))) else: button(fsymb, char, lambda t=text, c=char: t.set(t.get() c)) four_b = frame(root) # 創建第一行四個按鈕 button(four_b, '←',lambda t=text: t.set(back(t.get()))) button(four_b, 'Clear', lambda t=text: t.set('0')) #不加0,則按clear時不是歸零,是空白 button(four_b, '±', lambda t=text: t.set('-'))#這裡是顯示正負号 button(four_b, 'ON', lambda t=text: t.set('')) root.mainloop()

圖6


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)7

顯示框的顔色設定和字體顔色設定,還不會

7.第七例78行代碼

class Calculator: import tkinter as tk import tkinter.messagebox as mbox def __init__(self): self.window = self.tk.Tk() self.window.title('簡易計算器7') self.window.geometry("1020x800 500 0") self.label_show = self.tk.Label(text='', anchor='se', font=('黑體', 20), bg='black',fg='red') self.label_show.place(x=0, y=0, width=880,height=80) #通過width大小來改變顯示框的大小 self.set_buttons() self.window.mainloop() def set_buttons(self):#按鈕設置 x0, y0, x_width, y_width,height = 0, 90, 220, 80, 40 #通過x_width, y_width大小設置來改變按鈕的大小 b7 = self.tk.Button(text='7', bd=2, bg='pink',font='黑體') #第一層 b7.place(x=x0,y=y0,width=x_width, height=y_width) b8 = self.tk.Button(text='8', bd=2, bg='pink',font='黑體') b8.place(x=x0 x_width*1, y=y0,width=x_width,height=y_width) b9 = self.tk.Button(text='9', bd=2, bg='pink',font='黑體') b9.place(x=x0 x_width*2, y=y0,width=x_width,height=y_width) b_add = self.tk.Button(text=' ', bd=2, bg='pink',font='黑體') b_add.place(x=x0 x_width*3, y=y0,width=x_width,height=y_width) b4 = self.tk.Button(text='4', bd=2, bg='pink',font='黑體') #第二層 b4.place(x=x0,y=y0 y_width,width=x_width,height=y_width) b5 = self.tk.Button(text='5', bd=2, bg='pink',font='黑體') b5.place(x=x0 x_width*1, y=y0 y_width,width=x_width,height=y_width) b6 = self.tk.Button(text='6', bd=2, bg='pink',font='黑體') b6.place(x=x0 x_width*2, y=y0 y_width,width=x_width,height=y_width) b_subtract = self.tk.Button(text='-', bd=2, bg='pink',font='黑體') b_subtract.place( x=x0 x_width*3, y=y0 y_width,width=x_width,height=y_width) b1 = self.tk.Button(text='1', bd=2, bg='pink',font='黑體') #第三層 b1.place(x=x0,y=y0 y_width*2,width=x_width,height=y_width) b2 = self.tk.Button(text='2', bd=2,bg='pink', font='黑體') b2.place(x=x0 x_width*1, y=y0 y_width*2,width=x_width,height=y_width) b3 = self.tk.Button(text='3', bd=2, bg='pink',font='黑體') b3.place(x=x0 x_width*2, y=y0 y_width*2,width=x_width, height=y_width) b_mutiply = self.tk.Button(text='*', bd=2, bg='pink',font='黑體') b_mutiply.place(x=x0 x_width*3, y=y0 y_width*2, width=x_width,height=y_width) b0 = self.tk.Button(text='0', bd=2, bg='pink',font='黑體') #第四層 b0.place(x=x0,y=y0 y_width*3,width=x_width,height=y_width) bb = self.tk.Button(text='%', bd=2, bg='pink',font='黑體') bb.place(x=x0 x_width,y=y0 y_width*3,width=x_width,height=y_width) b_point = self.tk.Button(text='.', bd=2, bg='pink',font='黑體') b_point.place(x=x0 x_width*2, y=y0 y_width*3,width=x_width,height=y_width) b_divid = self.tk.Button(text='/', bd=2, bg='pink',font='黑體') b_divid.place(x=x0 x_width*3, y=y0 y_width*3,width=x_width,height=y_width) b_clear = self.tk.Button( text='clear', bd=2, bg='pink',font='黑體') #第五層 b_clear.place(x=x0,y=y0 y_width*4,width=x_width, height=y_width) b_back = self.tk.Button( text='←', bd=2,bg='pink', font='黑體') b_back.place(x=x0 x_width*1,y=y0 y_width*4,width=x_width, height=y_width) b_equal = self.tk.Button( text='=', bd=2,bg='orange', font='黑體') b_equal.place(x=x0 x_width*2, y=y0 y_width*4,width=x_width*2, height=y_width) b7.bind_class('Button', '<Button-1>', self.click_button) # 綁定Button的點擊事件 def click_button(self, event): input_event = event.widget['text'] self.label_show['text'] = self.label_show['text'] input_event try: cal_symbol = [' ', '-', '*', '/'] if self.label_show['text'][-1] in cal_symbol and self.label_show['text'][-2] in cal_symbol: header = self.label_show['text'][:-2] footer = self.label_show['text'][-1] self.label_show['text'] = header footer except: pass if event.widget['text'] == '=': try: res_bit = 2 # 計算保留的位數 res = eval(self.label_show['text'][:-1]) # 計算點擊 “=” 之前的計算表達式 self.label_show['text'] = str(round(float(res), res_bit)) except ZeroDivisionError: self.mbox.showerror(title='錯誤', message='老兄,除法計算時!除數不能為0!') except: self.mbox.showerror(title='未知名錯誤', message='老兄,算式錯誤,請檢查!') elif event.widget['text'] == '←': back_res = self.label_show['text'][:-5] # 點擊的‘back’也計算在内,它占4個字符,因此是倒數5位去掉 self.label_show['text'] = back_res elif event.widget['text'] == 'clear': self.label_show['text'] = '0' # 不加0,則清除後為空格 start = Calculator()

圖7


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)8

幾次方不行,不能通過比如2**3來計算

8,第八例83行代碼

from tkinter import * root = Tk() root.title("簡易計算器8") root.geometry("1020x800 500 0") def GetInputValue(ShowNumEntry, Value):#用來顯示值 ShowNumEntry.insert(END,Value) def GetNumOne():#按鈕1并顯示 GetInputValue(ShowNumEntry,"1") def GetNumTwo():#按鈕2并顯示 GetInputValue(ShowNumEntry,"2") def GetNumThree():#按鈕3并顯示 GetInputValue(ShowNumEntry,"3") def GetNumFour():#按鈕4并顯示 GetInputValue(ShowNumEntry,"4") def GetNumFive():#按鈕5并顯示 GetInputValue(ShowNumEntry,"5") def GetNumSix():#按鈕6并顯示 GetInputValue(ShowNumEntry,"6") def GetNumSeven():#按鈕7并顯示 GetInputValue(ShowNumEntry,"7") def GetNumEight():#按鈕8并顯示 GetInputValue(ShowNumEntry,"8") def GetNumNine():#按鈕9并顯示 GetInputValue(ShowNumEntry,"9") def GetNumZero():#按鈕0并顯示 GetInputValue(ShowNumEntry,"0") def GetDot():#按鈕.并顯示 GetInputValue(ShowNumEntry,".") def GetPlus():#按鈕 并顯示 GetInputValue(ShowNumEntry," ") def GetMinus():#按鈕-并顯示 GetInputValue(ShowNumEntry,"-") def GetClean():#清除 ShowNumEntry.delete(0,END) def GetMultiply():#按鈕*并顯示 GetInputValue(ShowNumEntry,"*") def GetDivision():#按鈕/并顯示 GetInputValue(ShowNumEntry,"/") def GetPec():#按鈕/并顯示 GetInputValue(ShowNumEntry,"%") #顯示% def GetResult():#計算結果并顯示 result = eval(ShowNumEntry.get()) GetClean() ShowNumEntry.insert(0,str(result)) ShowNumEntry = Entry(root, bg='black',fg='red',justify="right",width = 45,font=20) ShowNumEntry.grid(row=0, column=0,columnspan=6) #第一行 b1 = Button(root,text = "1",bg='pink',font=8, width = 6,height = 2,command = GetNumOne) b1.grid(row=1, column=0) b2 = Button(root,text = "2", bg='pink',font=8,width = 6,height = 2,command = GetNumTwo) b2.grid(row=1, column=1) b3 = Button(root,text = "3", bg='pink',font=8,width = 6,height = 2,command = GetNumThree) b3.grid(row=1, column=2) bj = Button(root,text = " ", bg='pink',font=8,width = 6,height = 2,command = GetPlus) bj.grid(row=1, column=3) bjh = Button(root,text = "-",bg='pink',font=8, width = 6,height = 2,command = GetMinus) bjh.grid(row=1, column=4) by = Button(root,text = "%",bg='pink', font=8,width = 6, height = 2, command = GetPec) by.grid(row=1, column=5) #第二行 b4 = Button(root,text = "4",bg='pink',font=8, width = 6,height = 2,command = GetNumFour) b4.grid(row=2, column=0) b5 = Button(root,text = "5",bg='pink', font=8,width = 6,height = 2,command = GetNumFive) b5.grid(row=2, column=1) b6 = Button(root,text = "6",bg='pink', font=8,width = 6,height = 2,command = GetNumSix) b6.grid(row=2, column=2) bd = Button(root,text = ".",bg='pink', font=8,width = 6,height = 2,command =GetDot) bd.grid(row=2, column=3) bch = Button(root,text = "*", bg='pink',font=8,width = 6,height = 2,command = GetMultiply) bch.grid(row=2, column=4) bxg = Button(root,text = "/",bg='pink', font=8,width = 6, height = 2, command = GetDivision) bxg.grid(row=2, column=5) #第三行 b7 = Button(root,text = "7",bg='pink',font=8,width = 6, height = 2, command = GetNumSeven) b7.grid(row=3, column=0) b8 = Button(root,text = "8",bg='pink', font=8,width = 6, height = 2, command = GetNumEight) b8.grid(row=3, column=1) b9 = Button(root,text = "9", bg='pink',font=8,width = 6, height = 2, command = GetNumNine) b9.grid(row=3, column=2) b0 = Button(root,text = "0",bg='pink',font=8, width = 6, height = 2, command = GetNumZero) b0.grid(row=3, column=3) bcl = Button(root,text = "Clear",bg='pink',font=8,width = 6,height = 2,command = GetClean) bcl.grid(row=3, column=4) bdy = Button(root,text = "=", bg='orange',font=8,width = 6, height = 2,command=GetResult) bdy.grid(row=3, column=5) root.mainloop()

圖8


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)9

9.第9例91行代碼

from tkinter import * #導出模塊 root=Tk() #定義窗口 root.title("簡易計算器9") root.geometry("1020x800 500 0") #代表500,0=x,y,水平線是0,頂上線,水平移動500,水平線向右移動500 class CreateFrame(): def __init__(self,frame,width,height): self.frame=frame self.width=width self.height=height def creat_frame(self): creat_frame=Frame(self.frame,width=self.width,height=self.height,bg='#ddd') return creat_frame class CreateButton(): def __init__(self): self.text=[['CE','Clear','←','%'],['*','/','-',' '],['0','1','2','3'],['4','5','6','7'],['8','9','.','=']] def create_button(self,frame): for i in range(0,5): for j in range(0,4): button1 =Button(frame, text=self.text[i][j], font=8,width=8, height=2, bg='pink')#按鈕大小和顔色設置 button1.grid(row=i, column=j, padx=3, pady=3) frame.pack() return button1 class CreatLabel(): def label(self,frame): label = Label(frame, bg='black',fg='red',font=('微軟雅黑', 15),width=30,anchor='e',text='0') label.pack( anchor='e') frame.pack() return label class BindBtton(): def btton_class_bind(self,button,label,label_frist): button.bind_class('Button','<Button-1>',lambda e: self(e,label,label_frist)) def __call__(self,e,label,label_frist): def change(): # 顯示運算表達式 if e.widget['text']=='.'and '.'in label['text']: if ' 'not in label['text']and '-'not in label['text']and '*'not in label['text']and '/'not in label['text']: return #判斷第一個數是不是能加小數點 if label['text'].count('.')==1 : #判斷第二個數是否能加小數點 label['text'] =label['text'] e.widget['text'] return label['text'] for i in label['text'].split(')')[1:]: #按括号分割 判斷第二數以後的表達式是否能加小數點 if '.'in i and i.count('.')==1: continue else: label['text'] = e.widget['text'] return label['text'] if label['text']=='0'and label['text']!='.': label['text'] =e.widget['text'] return label['text'] else: label['text']=label['text'] e.widget['text'] return label['text'] def operation():# 運算 if e.widget['text']=='=': if label['text'][-1] not in ' -*/=%': labe2['text']=eval(label['text']) label['text'] ='0' else: labe2['text'] = eval(label['text'][:-1]) elif ' 'in label['text']or '-'in label['text'] or '*'in label['text'] or '/'in label['text'] or '%'in label['text']: if e.widget['text']in ' -*/=%': if label['text'][-1] not in ' -*/=%': label['text']='(' label['text'] ')' e.widget['text'] label['text'] ='(' str(eval(label['text']) ) ')' e.widget['text'] else: label['text'] = e.widget['text'] else: label['text'] =e.widget['text'] def equal(): pass def delete(): label['text']=label['text'][:-1] #倒數第一切片删除 def clear(): #定義清除鍵的操作值 label['text']='0' labe2['text']='0' if e.widget['text'] in '1234567890.': change() elif e.widget['text'] in ['Clear']: clear() elif e.widget['text'] in ' -*/=%': operation() elif e.widget['text'] in '←': delete() frame1=CreateFrame(root,290,20).creat_frame() label=CreatLabel().label(frame1) frame3=CreateFrame(root,290,20).creat_frame() labe2=CreatLabel().label(frame3) frame2=CreateFrame(root,290,360) frame=frame2.creat_frame() button=CreateButton().create_button(frame) BindBtton().btton_class_bind(button,label,labe2) root.mainloop()

圖9


python怎麼用代碼寫一個計算器(100行代碼的簡易計算器大全)10

小數相加,第一個的0不能顯示;其次幾次方不行,未能通過比如2**3實現

總結:

有點長,非常經典,值得收藏,有興趣的可以熟悉熟悉,并自行解決。

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关科技资讯推荐

热门科技资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved