我在Python 3.4中编写了复杂的程序(使用tkinter gui)。它的温度转换器(摄氏温度到华氏温度和反向温度)是实时的。它的效果差不多,但有一个问题。每次输入值后我都要添加一个空格。任何人都知道这个程序有什么问题吗?
from tkinter import *
def cel_na_fahr(event):
e = ".0"
a = float(ent1.get())
a = round((32+9/5*a),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent2.delete(0,END)
ent2.insert(0,a+event.char)
else:
ent2.delete(0,END)
ent2.insert(0,a+event.char)
def fahr_na_cel(event):
e = ".0"
a = float(ent2.get())
a = round(5/9*(a-32),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent1.delete(0,END)
ent1.insert(0,a+event.char)
else:
ent1.delete(0,END)
ent1.insert(0,a+event.char)
root = Tk()
root.geometry("300x180+400+400")
fr1 = Frame(root, padx=5, pady=40)
fr1.pack(side=TOP)
fr2 = Frame(root)
fr2.pack(side=TOP)
lbl1 = Label(fr1, text="cel to fahr ")
lbl1.pack(side=LEFT)
ent1 = Entry(fr1)
ent1.pack(side=RIGHT)
lbl2 = Label(fr2, text="fahr to cel ")
lbl2.pack(side=LEFT)
ent2 = Entry(fr2)
ent2.pack(side=RIGHT)
ent1.bind('<Key>', cel_na_fahr)
ent2.bind('<Key>', fahr_na_cel)
root.mainloop()
答案 0 :(得分:3)
您必须键入空格,因为当<Key>
回调触发时,用户最近按下的键尚未添加到条目中。这可能是你试图通过添加event.char
来弥补的,尽管你在错误的地方做这件事。
将绑定更改为KeyRelease
,以便在条目更新后回调触发,并删除+event.char
内容,因为您不再需要它
from tkinter import *
def cel_na_fahr(event):
print(ent1.get())
e = ".0"
a = float(ent1.get())
a = round((32+9/5*a),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent2.delete(0,END)
ent2.insert(0,a)
else:
ent2.delete(0,END)
ent2.insert(0,a)
def fahr_na_cel(event):
print(ent2.get())
e = ".0"
a = float(ent2.get())
a = round(5/9*(a-32),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent1.delete(0,END)
ent1.insert(0,a)
else:
ent1.delete(0,END)
ent1.insert(0,a)
root = Tk()
root.geometry("300x180+400+400")
fr1 = Frame(root, padx=5, pady=40)
fr1.pack(side=TOP)
fr2 = Frame(root)
fr2.pack(side=TOP)
lbl1 = Label(fr1, text="cel to fahr ")
lbl1.pack(side=LEFT)
ent1 = Entry(fr1)
ent1.pack(side=RIGHT)
lbl2 = Label(fr2, text="fahr to cel ")
lbl2.pack(side=LEFT)
ent2 = Entry(fr2)
ent2.pack(side=RIGHT)
ent1.bind('<KeyRelease>', cel_na_fahr)
ent2.bind('<KeyRelease>', fahr_na_cel)
root.mainloop()