2016-12-04 55 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()