做一個計算器,這是我想要達成的效果:

在按下按鈕或者按下鍵盤的時候,第一行輸入框會顯示輸入的內容,第二行顯示框則會預覽運算結果,如果發生例外,輸入內容格式錯誤,無法計算,則顯示框顯示“錯誤”,
按“=”按鈕或按鍵回車計算結果,結果顯示在第一行,
1.準備作業
匯入庫 tkinter
import tkinter as tk
2. 開始
定義兩個變數:
equal_is=False #定義一些變數
textchange=''
equal_is 用于判斷是否已經計算出結果,textchange是用于設定輸入框的內容,
2.1 生成控制元件
首先生成表單:
root=tk.Tk() #創建表單
root.geometry('250x350')
root.title('計算器')
為了方便,在這里定義一個函式 create_btn
def create_btn(text,col,row,cs,rs,pri='',px=(1,1),py=(1,1)): #函式:生成按鈕
if pri=='':
t=text
else:
t=pri
a=tk.Button(root,text=text,width=4,command=lambda:(text_print(t))) #輸入內容
a.grid(column=col,row=row,columnspan=cs,rowspan=rs,padx=px,pady=py,sticky='nswe')
return(a)
因為有些按鈕的輸入內容并不等于它的文本內容(比如按鈕“×”,輸入“*”),因此我們設定一個空的引數 pri ,在 pri 沒有被賦值的時候,輸入內容則為 text ,
text_print 是輸入內容的函式,這個在后面會定義,
btn={} #生成按鈕
btn['1']=create_btn('1',0,5,1,1)
btn['2']=create_btn('2',1,5,1,1)
btn['3']=create_btn('3',2,5,1,1)
btn['4']=create_btn('4',0,4,1,1)
btn['5']=create_btn('5',1,4,1,1)
btn['6']=create_btn('6',2,4,1,1)
btn['7']=create_btn('7',0,3,1,1)
btn['8']=create_btn('8',1,3,1,1)
btn['9']=create_btn('9',2,3,1,1)
btn['0']=create_btn('0',0,6,2,1)
btn['.']=create_btn('.',2,6,1,1)
btn['=']=create_btn('=',4,5,1,2)
btn['+']=create_btn('+',3,6,1,1)
btn['-']=create_btn('-',3,5,1,1)
btn['*']=create_btn('×',3,4,1,1,pri='*')
btn['/']=create_btn('÷',4,4,1,1,pri='/')
btn['←']=create_btn('←',1,2,1,1)
btn['C']=create_btn('C',2,2,1,1)
btn['(']=create_btn('(',3,2,1,1)
btn[')']=create_btn(')',4,2,1,1)
btn['**2']=create_btn('x2',3,3,1,1,pri='**2')
btn['**(-1)']=create_btn('1/x',4,3,1,1,pri='**(-1)')
上面是用 create_btn 函式生成每一個按鈕,
la=tk.Label(root,text='',bg='white',fg='black',font=('宋體',24),anchor='w',relief='flat') #生成輸入框
la.grid(column=0,row=0,columnspan=5,rowspan=1,sticky='we')
lab=tk.Label(root,bg='white',fg='grey',height=1,font=('宋體',22),anchor='w',relief='flat') #生成顯示框
lab.grid(column=0,row=1,columnspan=5,rowspan=1,sticky='we')
上面創建兩個標簽,作為輸入框和顯示框,
la 是輸入框,lab是顯示框,
然后定義函式 grid_rowconfigure 和 grid_columnconfigure,用于自動填充行和列:
def grid_rowconfigure(*rows): #函式填充行,*rows:允許接收多個引數
for i in rows:
root.grid_rowconfigure(i,weight=1)
def grid_columnconfigure(*cols): #函式填充列,*cols:允許接收多個引數
for i in cols:
root.grid_columnconfigure(i,weight=1)
在表單被改變大小時,按鈕會自動填充四周,而輸入、顯示框只填充左右兩邊(第2,3,4,5,6行會向豎直方向填充,每一列都會向水平方向填充),
grid_rowconfigure(2,3,4,5,6)
grid_columnconfigure(0,1,2,3,4)
2.2 定義輸入和計算函式
定義 text_print 函式,當按鈕被點擊時輸入內容,當按鈕“=”被點擊的時候計算結果:
def text_print(x): #函式按鈕輸入算式
global textchange,equal_is #宣告全域變數
if x!='=':
if x=='←':
a=str(textchange)[0:-1]
textchange=a #退格
elif x=='C':
textchange='' #清空
else:
textchange=str(textchange)+str(x) #輸入
la.configure(text=textchange)
show_is()
equal_is=False #判斷格式有無錯誤
if x=='=':
text_equal() #計算結果
show_is 用于判斷格式有無錯誤:
def show_is(): #顯示框內容
global textchange #宣告全域變數
if textchange!='':
try:
textshow=eval(textchange)
except (SyntaxError,TypeError,NameError):
lab.configure(text='錯誤') #如果出錯了,則顯示“錯誤”
else:
lab.configure(text=textshow) #如果沒有出錯,則顯示結果
else:
lab.configure(text='') #如果輸入框為空,那么清空顯示框
text_equal 是計算結果的函式:
def text_equal(event=None): #函式計算結果并上到輸入框
global textchange,equal_is #宣告全域變數
if lab['text']!='錯誤' and equal_is==False:
textchange=lab['text'] #無格式錯誤時,計算結果
la.configure(text=textchange) #輸入框顯示結果
lab.configure(text='') #清空顯示框
equal_is=True
這里詳細說明一下 equal_is 的作用:
因為計算了結果后顯示框會清空,為了防止二次計算導致輸入框也跟著清空,我們需要判斷是否已經計算過結果,這時就用到變數 equal_is ,
當輸入內容時,equal_is 變為 True,計算結果后,equal_is 變為 False,如果 equal_is == True,則不計算結果,
2.3 系結鍵盤事件
我設定的鍵盤按鍵及其對應輸入內容:
| 輸入內容 | 對應按鍵 |
|---|---|
| 0~9 | 0~9 |
| + | + |
| - | - |
| * | * |
| / | / |
| 退格 | BackSpace |
| 清空 | Delete |
| 計算結果 | Return(Enter鍵) |
定義一個函式 bind_print,跟 text_print 有點相似,但有些不一樣(原諒我技術差,不知道別的方法,只能重新定義一個函式):
def bind_print(event): #函式鍵盤事件輸入算式
global textchange,equal_is
if event.keysym!='Return':
if event.keysym=='BackSpace': #如果按鍵名等于“BackSpace”(退格鍵),那么就退格
a=str(textchange)[0:-1]
textchange=a
elif event.keysym=='Delete': #清空
textchange=''
else:
textchange=str(textchange)+str(event.char) #輸入按鍵內容,char不會獲得Ctrl,Shift等特殊按鍵的文本
la.configure(text=textchange) #顯示內容
show_is() #判斷是否錯誤
equal_is=False
else:
text_equal()
如果按下的是特殊按鍵,除非是退格和回車,否則都不會有反應,
按下字母、數字、符號鍵的時候,輸入按鍵內容,
接下來就是系結鍵盤事件了:
root.bind('<Key>',bind_print) #當鍵盤按下任意鍵,執行bind_print
這樣,界面布置和功能就完成了‘
2.4 回圈
將主表單root放入主回圈中:
root.mainloop()
3.全部代碼
import tkinter as tk
def create_btn(text,col,row,cs,rs,pri='',px=(1,1),py=(1,1)): #函式生成按鈕
if pri=='':
t=text
else:
t=pri
a=tk.Button(root,text=text,width=4,command=lambda:(text_print(t)))
a.grid(column=col,row=row,columnspan=cs,rowspan=rs,padx=px,pady=py,sticky='nswe')
return(a)
def grid_rowconfigure(*rows): #函式填充行
for i in rows:
root.grid_rowconfigure(i,weight=1)
def grid_columnconfigure(*cols): #函式填充列
for i in cols:
root.grid_columnconfigure(i,weight=1)
def bind_print(event): #函式鍵盤事件輸入算式
global textchange,equal_is
if event.keysym!='Return':
if event.keysym=='BackSpace':
a=str(textchange)[0:-1]
textchange=a
elif event.keysym=='Delete':
textchange=''
else:
textchange=str(textchange)+str(event.char)
la.configure(text=textchange)
show_is()
equal_is=False
else:
text_equal()
def text_print(x): #函式按鈕輸入算式
global textchange,equal_is
if x!='=':
if x=='←':
a=str(textchange)[0:-1]
textchange=a
elif x=='C':
textchange=''
else:
textchange=str(textchange)+str(x)
la.configure(text=textchange)
show_is()
equal_is=False
if x=='=':
text_equal()
def text_equal(event=None): #函式計算結果并上到輸入框
global textchange,equal_is
if lab['text']!='錯誤' and equal_is==False:
textchange=lab['text']
la.configure(text=textchange)
lab.configure(text='')
equal_is=True
def show_is(): #顯示框內容
global textchange
if textchange!='':
try:
textshow=eval(textchange)
except (SyntaxError,TypeError,NameError):
lab.configure(text='錯誤')
else:
lab.configure(text=textshow)
else:
lab.configure(text='')
root=tk.Tk() #創建表單
root.geometry('250x350')
root.title('計算器')
root.bind('<Key>',bind_print)
equal_is=False #定義一些函式
textchange=''
la=tk.Label(root,text='',bg='white',fg='black',font=('宋體',24),anchor='w',relief='flat') #生成輸入框
la.grid(column=0,row=0,columnspan=5,rowspan=1,sticky='we')
lab=tk.Label(root,bg='white',fg='grey',height=1,font=('宋體',22),anchor='w',relief='flat') #生成顯示框
lab.grid(column=0,row=1,columnspan=5,rowspan=1,sticky='we')
btn={} #生成按鈕
btn['1']=create_btn('1',0,5,1,1)
btn['2']=create_btn('2',1,5,1,1)
btn['3']=create_btn('3',2,5,1,1)
btn['4']=create_btn('4',0,4,1,1)
btn['5']=create_btn('5',1,4,1,1)
btn['6']=create_btn('6',2,4,1,1)
btn['7']=create_btn('7',0,3,1,1)
btn['8']=create_btn('8',1,3,1,1)
btn['9']=create_btn('9',2,3,1,1)
btn['0']=create_btn('0',0,6,2,1)
btn['.']=create_btn('.',2,6,1,1)
btn['=']=create_btn('=',4,5,1,2)
btn['+']=create_btn('+',3,6,1,1)
btn['-']=create_btn('-',3,5,1,1)
btn['*']=create_btn('×',3,4,1,1,pri='*')
btn['/']=create_btn('÷',4,4,1,1,pri='/')
btn['←']=create_btn('←',1,2,1,1)
btn['C']=create_btn('C',2,2,1,1)
btn['(']=create_btn('(',3,2,1,1)
btn[')']=create_btn(')',4,2,1,1)
btn['**2']=create_btn('x2',3,3,1,1,pri='**2')
btn['**(-1)']=create_btn('1/x',4,3,1,1,pri='**(-1)')
grid_rowconfigure(2,3,4,5,6)
grid_columnconfigure(0,1,2,3,4)
root.mainloop()
4. 結束語
以上就是做一個簡單計算器的程序,效果如開頭所示,
本人技識訓較差,歡迎向我提出任何的意見,
豪·
2021.4.18
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/277748.html
標籤:其他
上一篇:2017藍橋杯C++A組——迷宮
