Home > Software engineering >  How to ask user for integer input using Python tkinter
How to ask user for integer input using Python tkinter

Time:05-29

I need to ask a user for an integer value and tried a=n.get() and then a=int(a) but it doesn't work as expected. Here the code I used:

def selectparamter():
    window3= Tk()
    window3.title('choosing parameters ')
    window3.resizable(False,False)
    a_label = Label(window3, text = 'Select  parameter', font=('calibre',10, 'bold'))
    n = Entry(window3)
    string_answer = n.get()
    a= int(string_answer)
    sub_btn=Button(window3,text = 'Submit', command =nrmltest )
    sub_btn.grid(row=2,column=1)
    a_label.grid(row=0,column=0)
    n.grid(row=0,column=1)
    window3.mainloop()
    return a

How can I get the right integer value input from user in Python tkinter?

CodePudding user response:

def selectparamter():
    window3= Tk()
    window3.title('choosing parameters ')
    window3.resizable(False,False)
    a_label = Label(window3, text = 'Select  parameter', font=('calibre',10, 'bold'))
    n_var = IntVar()
    n = Entry(window3, textvariable=n_var)
    a = n_var.get()
    sub_btn=Button(window3,text = 'Submit', command =nrmltest )
    sub_btn.grid(row=2,column=1)
    a_label.grid(row=0,column=0)
    n.grid(row=0,column=1)
    window3.mainloop()
    return a

For this code, IntVar class of tkinter was used to give value to "textvariable" attribute of widget. For more info, press here. This can return the value of Entry widget as class but it will throw exception if string is given in the widget. The value of 'a' seems to have been called right after widget creation. so, now with no text in widget, it will not perform properly.

CodePudding user response:

Here you are ("If anybody knows how to solve this pls answer"):

from tkinter import Tk, Label, Entry, Button, IntVar 
def selectparameter():
    def getValueFromUser():
        window3.quit()
    window3= Tk()
    window3.title('Choosing Parameters ')
    window3.resizable(False, False)
    a_label = Label(window3, text = 'Provide an integer value:  ', font=('calibre',10, 'bold'))
    n_var   = IntVar()
    n_var.set('')
    n = Entry(window3, textvariable = n_var)
    n.focus_set()
    sub_btn=Button(window3, text='Submit', command = getValueFromUser )
    sub_btn.grid(row=2,column=1)
    a_label.grid(row=0,column=0)
    n.grid(row=0,column=1)
    window3.mainloop()
    a = n_var.get()
    return a
print(selectparameter())

BUT ... tkinter comes with a method which is both simpler and also better suited to get an integer input from user as it checks the user input and asks the user again in case of detected non-integer value:

from tkinter import Tk, simpledialog
root=Tk()
root.withdraw()
intUserInput = simpledialog.askinteger(title="askinteger", prompt="integerInputPlease")
root.destroy()
print(intUserInput)
  • Related