如何使用Python tkinter向用户询问整数输入
我需要向用户询问整数值,然后尝试a = n.get()
,然后a = int(a)
,但它不按预期工作。在这里,我使用的代码:
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
如何从Python Tkinter中的用户获取正确的整数输入?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于此代码,使用TKINTER类的INTVAR类来为小部件的“ textvariable”属性赋予价值。有关更多信息,在此处按。
这可以返回入口小部件的值为类的值,但是如果窗口小部件中的字符串给出,它将抛出异常。
“ 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.
在这里您是:
但是:
tkinter
带有一种更简单又更适合从用户获得整数输入的方法:askInteger
。它检查用户输入,并再次询问用户输入一个非全能值:Here you are:
But:
tkinter
comes with a method which is both simpler and also better suited to get an integer input from the user:askinteger
. It checks the user input and asks the user again in case they input a non-integer value: