Home > Net >  get() function in Tkinter always returns 0
get() function in Tkinter always returns 0

Time:12-03

i want to get the contents of an entry box and when i use the .get() function it always return 0 doesnt matter what i write in the box

window1 = Tk()
window1.geometry("500x720 750 0")
entry1 = IntVar()
e1 = tk.Entry(window1, width=8,fg="darkblue", textvariable=entry1, font=('secular one', 13)).place(x=20, y=60)
num_of_diners = entry1.get()


def get_value():
    tk.Label(window1, text=num_of_diners, font=('secular one', 20)).place(x=300, y=510)


tk.Button(window1, text="calculate price", command=get_value, font=('secular one', 18), relief=(FLAT)).place(x=20, y=500)

window1.mainloop()

thats the code simplified a bit but its whats giving me problem for example if i write 4 in the entry box and then press the button it shows 0

CodePudding user response:

You need to call get() inside the get_value() function

UPDATE - I misread the code previously - this should work now.

FYI:

  1. You don't need an IntVar to store the value of the Entry, you can just call get() directly and do away with setting the textvariable parameter
  2. You should make a habit of declaring your widgets separately from adding them to a geometry manager (i.e. pack, grid, place). The geometry manager methods always return None, so something like my_entry = tk.Entry(root).pack() will always evaluate to None, which is probably not what you want
entry1 = tk.Entry(window1, width=8,fg="darkblue", font=('secular one', 13))
entry1.place(x=20, y=60)


def get_value():
    num_of_diners = int(entry1.get())  # get entry contents as an integer
    tk.Label(window1, text=num_of_diners, font=('secular one', 20)).place(x=300, y=510)

Bear in mind that if the contents of entry1 can't be cast to an int you'll get an exception. An easy way around this is:

def get_value():
    entry_content = entry1.get()
    if entry_content.isdigit():
        num_of_diners = int(entry_content)
    else:
        num_of_diners = 0  # fall back to 0 on conversion failure
  • Related