Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

สร้าง GUI Calculator เรียบง่ายด้วย Tkinter ใน Python

บทนำ

tkinter เป็น GUI toolkit built-in ของ Python สร้าง desktop apps ได้ง่าย

เตรียมความพร้อม

pip install Pillow  # สำหรับโหลดรูปไอคอน

โฟลเดอร์โครงสร้าง:

Working Directory/
  Calculator.py
  assets/
    Calculator/
      Logo.ico, one.PNG, two.PNG, ...

ฟังก์ชันหลัก

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():
    global txt, ans, res
    try:
        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)

    equation = StringVar()
    txt_field = Entry(relief=RIDGE, textvariable=equation, bd=10, font=("Arial", 20), bg="powder blue")
    txt_field.grid(columnspan=4, ipady=10, ipadx=10, sticky="nsew")

    # สร้างปุ่ม 0-9, +, -, *, /, =, clear ด้วยรูปภาพ
    width = 80
    height = 80
    # ... (โค้ดสร้างปุ่มแต่ละตัว ใช้ Image.open, resize, ImageTk.PhotoImage, Button, grid)
    window.mainloop()

คำอธิบาย

  • StringVar(): ตัวแปรผูกกับ Entry widget
  • eval(txt): คำนวณ expression string (⚠️ security risk ใน production)
  • ใช้รูปภาพเป็นปุ่ม (ImageTk.PhotoImage) วางด้วย grid layout
  • sticky="nsew": ขยายเต็ม cell

ผลลัพธ์

Calculator GUI สีดำ พร้อมปุ่มตัวเลข/สัญลักษณ์/เคลียร์/เท่ากับ ทำงานได้จริง

โค้ดเต็ม

ดูที่ GitHub: Simple Calculator.py