Python - 我想要两个条目小部件 Sum 而不使用按钮

Python - I want two entry widgets Sum without using button

我不明白该怎么做。我需要对两个条目求和,然后将总和放入另一个没有任何按钮的条目小部件中。

例子一

from tkinter import *
def sum():
a=float(t1.get())
b=float(t2.get())
c=a+b
t3.insert(0,c)
win=Tk()
win.geometry('850x450')

l1=Label(win,text="First Number")
l1.grid(row=0,column=0)
t1=Entry(win)
t1.grid(row=0,column=1)

l2=Label(win,text="Second Number")
l2.grid(row=1,column=0)
t2=Entry(win)
t2.grid(row=1,column=1)

l3=Label(win,text="Result")
l3.grid(row=2,column=0)
t3=Entry(win)
t3.grid(row=2,column=1)

b1=Button(win,text="Click For SUM",command=sum)
b1.grid(row=3,column=1)

win.mainloop()

我希望任何人都可以处理这个..

提前致谢..

没有任何按钮,您可能想使用 bind。所以试着在你的代码末尾说这个。

t2.bind('<Return>',sum)

并将函数更改为:

def sum(event):
..... #same code

现在您可以删除按钮,当您在第二个条目小部件中按 Enter 键时,它会调用 sum(),然后将输出插入到第三个条目小部件。

额外提示:

  • 我建议将函数名称从 sum 更改为其他名称,因为 sum 是一个 built-in python 函数。
  • 您还可以添加一个额外的 bind,例如 t1.bind('Return',lambda event:t2.focus_force()) 这样当用户在第一个条目中按下回车键时,他们将移动到下一个条目小部件(与 Tab 键相同) .

希望对您有所帮助,如有任何疑问,请告诉我。

干杯

你可以运行一个函数,每隔一秒定期将第三个条目的值重置为第一个和第二个条目的总和,就像这样-:

try :
    import tkinter as tk # Python 3
except :
    import Tkinter as tk # Python 2

def update_sum() :
    # Sets the sum of values of e1 and e2 as val of e3
    try :
        sum_tk.set((int(e1_tk.get().replace(' ', '')) + int(e2_tk.get().replace(' ', ''))))
    except :
        pass
    
    root.after(1000, update_sum) # reschedule the event
    return

root = tk.Tk()

e1_tk = tk.StringVar(root) # Initializes a text variable of tk to use to get e1's val.
e2_tk = tk.StringVar(root) # Initializes a text variable of tk to use to get e2's val.
sum_tk = tk.StringVar(root) # Initializes a text variable of tk to use to set e3's val.

# Entries
e1 = tk.Entry(root, textvariable = e1_tk)
e2 = tk.Entry(root, textvariable = e2_tk)
e3 = tk.Entry(root, textvariable = sum_tk)

e1.pack()
e2.pack()
e3.pack()

# Will update the sum every second 1000 ms = 1 second it takes ms as arg.
root.after(1000, update_sum)
root.mainloop()

您可以根据需要调整更新之间的延迟。