这里使用tkinter进行界面处理,方便快捷~大家可以参考:用Python基于tkinter模拟QQ界面之QQ登录界面的奥秘
# 计算器
import tkinter as tk
win = tk.Tk()
win.title('硅谷计算器')
win.geometry('280x500')
# 标签
la1 = tk.Label(
win,
font=(None, 20),
bg="#98F1FF",
fg="#000000",
bd=1,
anchor='se', # 船锚 east south west north
text="显示结果",
)
la1.place(x=0, y=0, width=280, height=100)
la2 = tk.Label(
win,
font=(None, 20),
bg="#98F1FF",
fg="#000000",
bd=1,
anchor="se",
text="显示公式"
)
la2.place(x=0, y=100, width=280, height=100)
remember = ""
def press(t):
global remember
remember += t
la2["text"] = remember
def equal():
global remember
la1["text"] = eval(remember)
def clean():
global remember
remember = ""
la1["text"] = "显示结果"
la2["text"] = "显示公式"
def back():
global remember
if remember == "":
la2["text"] = "显示公式"
else:
remember = remember[0:-1]
la2["text"] = remember
def btn(t, x, y, color="#0000FF", width=70, height=60):
symbol = t
if t == "×":
symbol = "*"
elif t == "÷":
symbol = "/"
function = lambda: press(symbol)
if t == "=":
function = lambda: equal()
elif t == "AC":
function = lambda: clean()
elif t == "←":
function = lambda: back()
btn_back = tk.Button(
win,
text=t,
font=(None, 20),
fg=color,
command=function # 命令,指向一个函数
)
btn_back.place(x=x, y=y, width=width, height=height)
# 第一行按钮
btn("AC", 0, 200, color="#FF0000")
btn("←", 70, 200, color="#FF0000")
btn("÷", 140, 200)
btn("×", 210, 200)
# 第二行按钮
btn("7", 0, 260)
btn("8", 70, 260)
btn("9", 140, 260)
btn("-", 210, 260)
# 第三行按钮
btn("4", 0, 320)
btn("5", 70, 320)
btn("6", 140, 320)
btn("+", 210, 320)
# 第四行按钮
btn("1", 0, 380)
btn("2", 70, 380)
btn("3", 140, 380)
btn("=", 210, 380, color="#FF0000", height=120)
# 第五行按钮
btn("%", 0, 440, width=35)
btn(".", 35, 440, width=35)
btn("0", 70, 440)
btn("(", 140, 440, width=35)
btn(")", 175, 440, width=35)
win.mainloop()
更多精彩内容