今天看了小甲鱼的视频,发现了计算器还可以这样做,感觉很奇葩,另外学习了下,
小甲鱼原版代码如下:
#!/usr/bin/python
#coding: utf-8
from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack(padx = 10, pady = 10)
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
def test(content):
# 如果是数字,返回真,否则返回假
return content.isdigit()
# 把test函数包装起来,用于validatecommand中
testCMD = root.register(test)
Entry(frame,
textvariable = v1, # 设置当v1的值改变的时候,当前框体中的值也发生变化
validate = "key", # 当在输入框输入东西的时候直接进行验证
validatecommand = (testCMD, "%P"),
).grid(row = 0, column = 0)
Label(frame, text = "+").grid(row = 0, column = 1)
Entry(frame,
textvariable = v2,
validate = "key",
validatecommand = (testCMD, "%P"),
).grid(row = 0, column = 2)
Label(frame, text = "=").grid(row = 0, column = 3)
Entry(frame,
textvariable = v3,
state = "readonly" # 设置不能修改这个框体中的值
).grid(row = 0, column = 4)
def calc():
result = int(v1.get()) + int(v2.get())
return v3.set(str(result))
Button(frame, text = "计算结果", command = calc).grid(row = 1, column = 2)
root.mainloop()
#!/usr/bin/python
#coding: utf-8
from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack(padx = 10, pady = 10)
# Label(frame, text = "简易计算器", font = ("宋体", 20)).grid(row = 0, column = 2)
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
def test(content):
# 如果是数字,返回真,否则返回假
return content.isdigit()
# 把test函数包装起来,用于validatecommand中
testCMD = root.register(test)
Entry(frame,
textvariable = v1, # 设置当v1的值改变的时候,当前框体中的值也发生变化
validate = "key", # 当在输入框输入东西的时候直接进行验证
validatecommand = (testCMD, "%P"),
).grid(row = 2, column = 0)
v = IntVar()
calcs = [
('+', 1),
('-', 2),
("*", 3),
("/", 4),
("%", 5)
]
for _calc, num in calcs:
# 设置单选框,用来显示运算符
Radiobutton(frame,
text = _calc,
variable = v,
value = num).grid(row = num - 1, column = 1, sticky = W)
Entry(frame,
textvariable = v2,
validate = "key",
validatecommand = (testCMD, "%P"),
).grid(row = 2, column = 2)
Label(frame, text = "=").grid(row = 2, column = 3)
Entry(frame,
textvariable = v3,
state = "readonly" # 设置不能修改这个框体中的值
).grid(row = 2, column = 4)
def judge(x, y, z):
if y == 1:
return x + z
elif y == 2:
return x - z
elif y == 3:
return x * z
elif y == 4:
t = x / z
return (x / z) if t * z == x else (x * 1.0 / z)
elif y == 5:
return x % z
def calc():
# 根据calcs列表中的值来判断此时的计算符号
s = int(v.get())
result = judge(int(v1.get()), s, int(v2.get()))
return v3.set(str(result))
Button(frame, text = "计算结果",
width = 10,
command = calc).grid(row = 3, column = 2)
Button(frame,
text = "退出",
width = 10,
command = root.quit).grid(row = 3, column = 4)
root.mainloop()
当然,还可以增加更多的功能,把旁边的那些没用的区域找东西给替换了,这样界面更完美,还有就是弄一个菜单选项等等,有兴趣的读者自己去尝试啦!!!!