2017-09-07 51 views
1

我正在使用tkinter编写GUI的简单代码。我的问题是,我想要一个数字,打印在名为t1的标签中,总是按给出的两个条目的总和进行更新。当然,我不能在条目中使用.get方法,因为我会在调用方法时修复值,但我不知道使用其他Intvar构建新的(始终更新的)IntVar是否热门。GUI中的值更新

from tkinter import * 
window=Tk() 

p1_in=StringVar() 
p1=Entry(window,textvariable=p1_in) 

p2_in=StringVar() 
p2=Entry(window,textvariable=p2_in) 

t1=Label(window,textvariable=(p1_in+p2_in)) # of course this doesn't work 
t1.grid(row=7,column=2) 

window.mainloop() 

如何使标签t1始终与p1_in + p2_in之和一起更新? 我知道他们是StringVar,但输出更适合我的意图这种方式,再加上我不认为这是主要问题

回答

1

您可以使用StringVar的跟踪方法。它在值更改后立即被调用。

from tkinter import * 
window=Tk() 

def calculate(*args): 
    if p1_in.get() and p2_in.get(): #checks if both are not empty 
     try: 
      ans = int(p1_in.get()) + int(p2_in.get()) 
      t1_out.set(str(ans)) 
     except ValueError: 
      t1_out.set("Enter integers!") 

p1_in=StringVar() 
p1=Entry(window,textvariable=p1_in) 
p1_in.trace("w", calculate) 

p2_in=StringVar() 
p2=Entry(window,textvariable=p2_in) 
p2_in.trace("w", calculate) 

t1_out=StringVar() 

t1=Label(window,textvariable=t1_out) #also note that used another variable for output 
t1.grid(row=7,column=2) 
p1.grid(row=5,column=2) 
p2.grid(row=6,column=2) 

window.mainloop()