2016-12-04 63 views
1

我有这个代码,基本上我想要做的是我想按下按钮时,按钮上的余额更新的金额。如果余额现在是15,而我加10,我希望它增加10。如何让此按钮更新余额?

from tkinter import * 

def bal(): 
    ans = int (input1.get()) 
    total = IntVar() 
    tot = int (total.get()) 
    tot = tot + ans 
    res.set(tot+ans) 

root = Tk() 
root.geometry("1280x720") 

upper = Frame(root) 
upper.pack() 

Label(upper, text ="Sum:", font = ('raleway', 15),).grid(row=0, column = 0) 
Label(root, text ="Balance:", font = ('raleway', 15)).place(rely=1.0, relx=0, x=0, y=0, anchor=SW) 

res = StringVar() 

input1 = Entry(upper) 
num2 = Entry(root) 

result = Label(root, textvariable = res,font = ('raleway',13)) 

result.place(rely=1.0, relx=0, x=80, y=-2, anchor=SW) 

input1.grid(row=0,column=2) 

Button(upper, text ="Add Funds", command = bal).grid(row=4, column=2, ipadx = 65) 

mainloop() 

root.mainloop() 

我试图有一个不断更新的函数bal,但它不会因某种原因更新。顺便说一下,我是一个Python初学者:D 感谢您的帮助!

回答

0

您创建了一个新的IntVar,并且您正在对此使用.get。相反,你想要使用num2获得当前存储在那里的数字,并在其中添加输入并更新var。

1

bal()命令功能,所有你需要做的是检索当前的输入值和运行总量(平衡),加在一起,然后更新运行总计:

from tkinter import * 

def bal(): 
    ans = input1.get() 
    ans = int(ans) if ans else 0 
    tot = int(res.get()) 
    tot = tot + ans 
    res.set(tot) 

root = Tk() 
root.geometry("1280x720") 

upper = Frame(root) 
upper.pack() 

Label(upper, text="Sum:", font=('raleway', 15)).grid(row=0, column=0) 
Label(root, text="Balance:", font=('raleway', 15)).place(rely=1.0, relx=0, 
                 x=0, y=0, anchor=SW) 
res = StringVar() 
res.set(0) # initialize to zero 
input1 = Entry(upper) 
result = Label(root, textvariable=res, font=('raleway', 13)) 
result.place(rely=1.0, relx=0, x=80, y=-2, anchor=SW) 
input1.grid(row=0,column=2) 
Button(upper, text="Add Funds", command=bal).grid(row=4, column=2, ipadx=65) 

root.mainloop()