无法获得Entry小部件的tkinter的价值

时间:2018-09-22 11:10:17

标签: python oop tkinter

这是我的输入小部件代码和单击按钮的代码

# Amount entry here
    textBoxAmount = Entry(win, textvariable=amount_entry)
    textBoxAmount.grid(row=2, column=1)

    # Deposit button here
    buttonDeposit = tk.Button(text="Deposit", command=perform_deposit())
    buttonDeposit.grid(row=2, column=2)

&我的函数perform_deposit

def perform_deposit():
    '''Function to add a deposit for the amount in the amount entry to the
       account's transaction list.'''
    global account
    global amount_entry
    global balance_label
    global balance_var

    # Try to increase the account balance and append the deposit to the account file
    #input = amount_text.get("1.0",END)
    amount_entered = amount_entry.get()
    print("amount entered : {}".format(amount_entry.get()))
    print(amount_entered)
    #balance_var= account.deposit(amount_entry.get())
    print(balance_var)

输出就像

amount entered : 

在将200放入文本小部件时未获得textvariable值

1 个答案:

答案 0 :(得分:0)

此代码无法运行,所以我猜到了它的外观。

使用前,您需要创建StringVar() amount_entry。您可以在函数perform_deposit()之外执行此操作,而不必将其声明为global

将按钮与命令相关联时,不应包含括号,因为在声明按钮命令时该函数将运行该函数。

检查以下示例:

from tkinter import *

win = Tk()
win.geometry('300x200')

amount_entry = StringVar()

def perform_deposit():
    global balance_var
    amount_entered = amount_entry.get()
    print("amount entered : {}".format(amount_entry.get()))

# Amount entry here
textBoxAmount = Entry(win, textvariable=amount_entry)
textBoxAmount.grid(row=2, column=1)

# Deposit button here
buttonDeposit = Button(text="Deposit", command=perform_deposit)
buttonDeposit.grid(row=2, column=2)

win.mainloop()