使用Python的tkinter構建簡單的GUI計算器


介紹

在Python中,我們使用tkinter庫建立GUI元件並設計更好的使用者介面。

在本文中,您將學習構建基於GUI的簡單計算器應用程式的方法。

開始

在我們開始之前,我們需要先準備一些東西。

讓我們首先下載Python的影像庫,我們將使用它從本地系統獲取影像。為了安裝PIL(Pillow),啟動終端並輸入以下命令。

pip install Pillow

現在您已經安裝了包。您需要下載計算器所需的圖示。

您可以訪問谷歌圖片並下載所需的圖示。但是,如果您想要與我本專案中使用的圖示相同的圖示集,您可以從以下地址下載:

https://www.dropbox.com/sh/0zqd6zd9b8asmor/AAC3d2iOvMRl8INkbCuMUo_ya?dl=0。

確保您將所有圖示下載到名為“asset”的資料夾中。

接下來,我們需要匯入所需的模組。

from tkinter import *
from PIL import Image # pip install Pillow
from PIL import ImageTk

就是這樣。您現在應該已經準備好所有東西並可以開始使用了。

建立函式

首先,我們必須建立GUI元件將使用的函式。

主要有三個函式:按下數字或符號時呼叫一個函式,按下等號按鈕時呼叫另一個函式,最後按下清除按鈕時呼叫一個函式。

讓我們首先初始化一些全域性變數:

txt = ""
res = False
ans = 0

示例

按下數字鍵時呼叫的函式:

def press(num):
   global txt, ans, res
   if (res==True):
      txt = ans
      res = False
   txt = txt + str(num)
   equation.set(txt)

示例1

按下等號按鈕時呼叫的函式:

def equal():
   try:
      global txt, ans, res
      ans = str(eval(txt))
      equation.set(ans)
      res = True
   except:
      equation.set("ERROR : Invalid Equation")
      txt=""

按下清除按鈕時呼叫的函式:

示例

def clear():
   global txt, ans, res
   txt = ""
   equation.set("")
   res = False

現在我們已經定義了函式,我們可以啟動主函式並開始處理GUI元件。

if __name__ == "__main__":
   window = Tk()
   window.configure(background="black")
   window.title("Calculator")
   window.iconbitmap("assets\Calculator\Logo.ico")
   window.geometry("343x417")
   window.resizable(0,0)

以上程式碼行將構建一個完美的計算器。

注意 - 為了避免出現錯誤,請確保您遵循與上述程式碼相同的精確檔案結構。將logo圖示儲存在Calculator資料夾中,該資料夾位於assets資料夾內。

請按照以下格式:

+---Working Directory
   +---Calculator.py
   +---assets
      +---Calculator
         +---All the icons.

接下來,讓我們設計一個文字欄位,用於顯示數字。

equation = StringVar()

txt_field = Entry(relief=RIDGE,textvariable=equation,bd=10,font=("Aerial",20),bg="powder blue")

txt_field.grid(columnspan=4,ipady=10,ipadx=10,sticky="nsew")

現在,我們將重複新增圖示到GUI視窗的過程,一次一個。下面是一個例子,請按照此步驟操作其餘部分,或者直接從本文末尾的完整程式碼中複製。

示例

width=80
height=80
img1 = Image.open("assets/Calculator/one.PNG")
img1 = img1.resize((width,height))
oneImage = ImageTk.PhotoImage(img1)
button1 = Button(window, image=oneImage,bg="white",command = lambda:press(1),height=height,width=width)
button1.grid(row=2,column=0,sticky="nsew")

與以上程式碼行類似,對button2、button3等按鈕重複此操作,直到涵蓋所有數字和符號。

就是這樣。如果您現在執行程式,您應該會看到一個非常抽象的計算器。

如果您無法按照步驟操作,您可以從下面獲取完整的程式碼。

示例

from tkinter import *
from PIL import Image
from PIL import ImageTk

txt = ""
res = False
ans = 0

def press(num):
   global txt, ans, res
   if (res==True):
      txt = ans
      res = False
   txt = txt + str(num)
   equation.set(txt)
def equal():
   try:
      global txt, ans, res
      ans = str(eval(txt))
      equation.set(ans)
      res = True
   except:
      equation.set("ERROR : Invalid Equation")
      txt=""
def clear():
   global txt, ans, res
   txt = ""
   equation.set("")
   res = False
if __name__ == "__main__":
   window = Tk()
   window.configure(background="black")
   window.title("Calculator")
   window.iconbitmap("assets\Calculator\Logo.ico")
   window.geometry("343x417")
   window.resizable(0,0)
   equation = StringVar()
   txt_field = Entry(relief=RIDGE,textvariable=equation,bd=10,font=("Aerial",20),bg="powder blue")
   txt_field.grid(columnspan=4,ipady=10,ipadx=10,sticky="nsew")
   width=80
   height=80
   img1 = Image.open("assets/Calculator/one.PNG")
   img1 = img1.resize((width,height))
   oneImage = ImageTk.PhotoImage(img1)
   button1 = Button(window, image=oneImage,bg="white",command =          lambda:press(1),height=height,width=width)
   button1.grid(row=2,column=0,sticky="nsew")
   img2 = Image.open("assets/Calculator/two.PNG")
   img2 = img2.resize((width,height))
   twoImage = ImageTk.PhotoImage(img2)
   button2 = Button(window, image=twoImage,bg="white",command =    lambda:press(2),height=height,width=width)
   button2.grid(row=2,column=1,sticky="nsew")
   img3 = Image.open("assets/Calculator/three.PNG")
   img3 = img3.resize((width,height))
   threeImage = ImageTk.PhotoImage(img3)
   button3 = Button(window, image=threeImage,bg="white",command =    lambda:press(3),height=height,width=width)
   button3.grid(row=2,column=2,sticky="nsew")
   img4 = Image.open("assets/Calculator/four.PNG")
   img4 = img4.resize((width,height))
   fourImage = ImageTk.PhotoImage(img4)
   button4 = Button(window, image=fourImage,bg="white",command =    lambda:press(4),height=height,width=width)
   button4.grid(row=3,column=0,sticky="nsew")
   img5 = Image.open("assets/Calculator/five.PNG")
   img5 = img5.resize((width,height))
   fiveImage = ImageTk.PhotoImage(img5)
   button5 = Button(window, image=fiveImage,bg="white",command =    lambda:press(5),height=height,width=width)
   button5.grid(row=3,column=1,sticky="nsew")
   img6 = Image.open("assets/Calculator/six.PNG")
   img6 = img6.resize((width,height))
   sixImage = ImageTk.PhotoImage(img6)
   button6 = Button(window, image=sixImage,bg="white",command =    lambda:press(6),height=height,width=width)
   button6.grid(row=3,column=2,sticky="nsew")
   img7 = Image.open("assets/Calculator/seven.PNG")
   img7 = img7.resize((width,height))
   sevenImage = ImageTk.PhotoImage(img7)
   button7 = Button(window, image=sevenImage,bg="white",command =    lambda:press(7),height=height,width=width)
   button7.grid(row=4,column=0,sticky="nsew")
   img8 = Image.open("assets/Calculator/eight.PNG")
   img8 = img8.resize((width,height))
   eightImage = ImageTk.PhotoImage(img8)
   button8 = Button(window, image=eightImage,bg="white",command =    lambda:press(8),height=height,width=width)
   button8.grid(row=4,column=1,sticky="nsew")
   img9 = Image.open("assets/Calculator/nine.PNG")
   img9 = img9.resize((width,height))
   nineImage = ImageTk.PhotoImage(img9)
   button9 = Button(window, image=nineImage,bg="white",command =    lambda:press(9),height=height,width=width)
   button9.grid(row=4,column=2,sticky="nsew")
   img0 = Image.open("assets/Calculator/zero.PNG")
   img0 = img0.resize((width,height))
   zeroImage = ImageTk.PhotoImage(img0)
   button0 = Button(window, image=zeroImage,bg="white",command =    lambda:press(0),height=height,width=width)
   button0.grid(row=5,column=1,sticky="nsew")
   imgx = Image.open("assets/Calculator/multiply.PNG")
   imgx = imgx.resize((width,height))
   multiplyImage = ImageTk.PhotoImage(imgx)
   buttonx = Button(window, image=multiplyImage,bg="white",command =    lambda:press("*"),height=height,width=width)
   buttonx.grid(row=2,column=3,sticky="nsew")
   imgadd = Image.open("assets/Calculator/add.PNG")
   imgadd = imgadd.resize((width,height))
   addImage = ImageTk.PhotoImage(imgadd)
   buttonadd = Button(window, image=addImage,bg="white",command =    lambda:press("+"),height=height,width=width)
   buttonadd.grid(row=3,column=3,sticky="nsew")
   imgdiv = Image.open("assets/Calculator/divide.PNG")
   imgdiv = imgdiv.resize((width,height))
   divImage = ImageTk.PhotoImage(imgdiv)
   buttondiv = Button(window, image=divImage,bg="white",command =    lambda:press("/"),height=height,width=width)
   buttondiv.grid(row=5,column=3,sticky="nsew")
   imgsub = Image.open("assets/Calculator/subtract.PNG")
   imgsub = imgsub.resize((width,height))
   subImage = ImageTk.PhotoImage(imgsub)
   buttonsub = Button(window, image=subImage,bg="white",command = lambda:press("-   "),height=height,width=width)
   buttonsub.grid(row=4,column=3,sticky="nsew")
   imgeq = Image.open("assets/Calculator/equal.PNG")
   imgeq = imgeq.resize((width,height))
   eqImage = ImageTk.PhotoImage(imgeq)
   buttoneq = Button(window, image=eqImage,bg="white",command = equal,height=height,width=width)
   buttoneq.grid(row=5,column=2,sticky="nsew")
   imgclear = Image.open("assets/Calculator/clear.PNG")
   imgclear = imgclear.resize((width,height))
   clearImage = ImageTk.PhotoImage(imgclear)
   buttonclear = Button(window, image=clearImage,bg="white",command =    clear,height=height,width=width)
buttonclear.grid(row=5,column=0,sticky="nsew")

window.mainloop()

如果您在上述程式中遇到格式問題,也可以從https://github.com/SVijayB/PyHub/blob/master/Graphics/Simple%20Calculator.py獲取。

輸出

更新於:2021年2月11日

698 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告