Giới thiệu
Dùng thư viện tkinter tạo GUI Python. Xây dựng ứng dụng máy tính đơn giản.
Chuẩn bị
pip install Pillow
Tải icon vào folder assets/Calculator/.
Import
from tkinter import * from PIL import Image, ImageTk
Các hàm chính
txt = ""
res = False
ans = 0
def press(num):
global txt, ans, res
if res: 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 chính
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")
# Tạo các nút 0-9, + - * /, =, C với icon resize 80x80
# (code lặp lại cho từng nút, xem ví dụ đầy đủ ở cuối)
window.mainloop()
Lưu ý cấu trúc thư mục:
Working Directory
+-- Calculator.py
+-- assets
+-- Calculator
+-- Logo.ico, one.PNG, two.PNG, ..., equal.PNG, clear.PNG
Ví dụ đầy đủ
(Code hoàn chỉnh tạo 16 nút: 0-9, +, -, *, /, =, C – xem source gốc hoặc GitHub: Simple Calculator.py)
Kết quả
