Python tkinter .get method

1.2k views Asked by At

I'm trying to make a simple app that when you place a value it either adds to the total value or subtracts from it. At this point, I made a simple format but can't get the .get method to work. This error shows up AttributeError: 'NoneType' object has no attribute 'get' on line 29. Thank you for your help in advance!

Here is the code:

#PP2_Savings_App2

import tkinter as tk



root = tk.Tk()
root.geometry('500x300')
root.title('Savings App')


#Label

deposit_label = tk.Label(root, text='Deposit').grid(column=2, row=3)

withdraw_label = tk.Label(root, text='Withdraw').grid(column=6, row=3)

#Entry

deposit_entry = tk.Entry(root).grid(column=2, row=4)

withdraw_entry = tk.Entry(root).grid(column=6, row=4)

#Class/def and buttons

def deposit():

    amount_display = tk.Text(root, width=5, height=5).grid(column=7, row=2)
    responce_text = 'You deposited ${}'.format(deposit_entry.get())
    amount_display.insert(tk.END, responce_text)

deposit_button = tk.Button(master=root, text='Deposit', command=deposit).grid(column=2, row=5)

def withdraw():
    pass

withdraw_button = tk.Button(master=root, text='Withdraw', command=withdraw).grid(column=6, row=5)



root.mainloop()
1

There are 1 answers

1
cdlane On

@eugenhu explained the problem but you only applied the fix once, not everywhere it was needed:

If you don't need a handle onto a widget after its creation, you can do:

tk.Label(root, text='Deposit').grid(column=2, row=3)

but if you need a handle onto it going forward, you need to do:

deposit_entry = tk.Entry(root)
deposit_entry.grid(column=2, row=4)

but you can't do:

amount_display = tk.Text(root, width=5, height=5).grid(column=7, row=2)

and expect any good to come of it as the variable will be set to the result of the .grid() method invocation which is always None.

Your code reworked:

import tkinter as tk

def deposit():
    amount_display = tk.Text(root, width=5, height=5)
    amount_display.grid(column=7, row=2)
    response_text = 'You deposited ${}'.format(deposit_entry.get())
    amount_display.insert(tk.END, response_text)

def withdraw():
    pass

root = tk.Tk()
root.geometry('500x300')
root.title('Savings App')

# Labels

tk.Label(root, text='Deposit').grid(column=2, row=3)
tk.Label(root, text='Withdraw').grid(column=6, row=3)

# Entries

deposit_entry = tk.Entry(root)
deposit_entry.grid(column=2, row=4)

withdraw_entry = tk.Entry(root)
withdraw_entry.grid(column=6, row=4)

# Buttons

tk.Button(master=root, text='Deposit', command=deposit).grid(column=2, row=5)
tk.Button(master=root, text='Withdraw', command=withdraw).grid(column=6, row=5)

root.mainloop()