刚刚学习tkinter中的Entry组件问题
from tkinter import *root = Tk()
root.title("液柱压力计算")
frame = Frame(root)
frame.pack(padx=20,pady=20)
v1 =StringVar()
v2 =StringVar()
v3 =StringVar()
v4 =StringVar()
def test(content):
if content.isdigit():
return True
else:
return False
testCMD =root.register(test)
Label(frame,text="液柱垂深(m):",font=("宋体",20)).grid(row=0,column=0)
Entry(frame,textvariable=v1,width=20,validate="key",validatecommand=(testCMD,'%P')).grid(row=0,column=1)
Label(frame,text="液体密度(g/cm3):",font=("宋体",20)).grid(row=1,column=0)
Entry(frame,textvariable=v2,width=20,validate="key",validatecommand=(testCMD,'%P')).grid(row=1,column=1)
Label(frame,text="液柱压力(MPa):",font=("宋体",20)).grid(row=3,column=0)
Entry(frame,textvariable=v3,width=20,validate="key",validatecommand=(testCMD,'%P')).grid(row=3,column=1)
Label(frame,text="液柱压力(psi):",font=("宋体",20)).grid(row=4,column=0)
Entry(frame,textvariable=v4,width=20,validate="key",validatecommand=(testCMD,'%P')).grid(row=4,column=1)
def calc():
result1 = float(v1.get()) *float(v2.get())*9.8/1000
v3.set(result1)
v4.set(result1*145.037)
def test_empty():
v1.set("")
v2.set("")
v3.set("")
v4.set("")
Button(frame,text="计算结果",command=calc,font=("宋体",14),fg="red").grid(row=2,column=1,pady=5)
Button(frame,text="重 置",command=test_empty,font=("宋体",14),fg="red").grid(row=2,column=0,pady=5)
mainloop()
刚刚学习了Etry组件,学着写了个简单的计算器,怎样修改让输入框里只能写入小数,test() 用 try-except
from tkinter import *
root = Tk()
root.title("液柱压力计算")
frame = Frame(root)
frame.pack(padx=20, pady=20)
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
v4 = StringVar()
def test(content):
if not content:
return True
try:
float(content)
return True
except ValueError:
return False
testCMD = root.register(test)
Label(frame, text="液柱垂深(m):", font=("宋体", 20)).grid(row=0, column=0)
Entry(frame, textvariable=v1, width=20, validate="key", validatecommand=(testCMD, '%P')).grid(row=0, column=1)
Label(frame, text="液体密度(g/cm3):", font=("宋体", 20)).grid(row=1, column=0)
Entry(frame, textvariable=v2, width=20, validate="key", validatecommand=(testCMD, '%P')).grid(row=1, column=1)
Label(frame, text="液柱压力(MPa):", font=("宋体", 20)).grid(row=3, column=0)
Entry(frame, textvariable=v3, width=20, validate="key", validatecommand=(testCMD, '%P')).grid(row=3, column=1)
Label(frame, text="液柱压力(psi):", font=("宋体", 20)).grid(row=4, column=0)
Entry(frame, textvariable=v4, width=20, validate="key", validatecommand=(testCMD, '%P')).grid(row=4, column=1)
def calc():
result1 = float(v1.get()) * float(v2.get()) * 9.8 / 1000
v3.set(result1)
v4.set(result1 * 145.037)
def test_empty():
v1.set("")
v2.set("")
v3.set("")
v4.set("")
Button(frame, text="计算结果", command=calc, font=("宋体", 14), fg="red").grid(row=2, column=1, pady=5)
Button(frame, text="重 置", command=test_empty, font=("宋体", 14), fg="red").grid(row=2, column=0, pady=5)
mainloop() zltzlt 发表于 2020-8-19 11:57
用 try-except
谢谢大佬
页:
[1]