Python 如何从 tkinter 输入框中获取整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32171005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get an integer from a tkinter entry box?
提问by
I am trying to work out how to get a value from a tkinter entry box, and then store it as a integer. This is what I have:
我正在尝试解决如何从 tkinter 输入框中获取值,然后将其存储为整数。这就是我所拥有的:
AnswerVar = IntVar()
AnswerBox = Entry(topFrame)
AdditionQuestionLeftSide = random.randint(0, 10)
AdditionQuestionRightSide = random.randint(0, 10)
AdditionQuestionRightSide = Label(topFrame, text= AdditionQuestionRightSide).grid(row=0,column=0)
AdditionSign = Label(topFrame, text="+").grid(row=0,column=1)
AdditionQuestionLeftSide= Label(topFrame, text= AdditionQuestionLeftSide).grid(row=0,column=2)
EqualsSign = Label(topFrame, text="=").grid(row=0,column=3)
AnswerBox.grid(row=0,column=4)
answerVar = AnswerBox.get()
root.mainloop()
(
)
I want to take then input from AnswerBox, and store it in the integer variable "answer". How can I do this?
我想从 AnswerBox 获取然后输入,并将其存储在整数变量“answer”中。我怎样才能做到这一点?
Thanks
谢谢
采纳答案by Bryan Oakley
Since you have an IntVar
associated with the entry widget, all you need to do is get the value of that object with the get
method:
由于您有一个IntVar
与条目小部件相关联,您需要做的就是使用以下get
方法获取该对象的值:
int_answer = answer.get()
If you don't use an IntVar
, you can get the value of the entry widget and the convert it to an integer with int
:
如果不使用IntVar
,则可以获取条目小部件的值并将其转换为整数int
:
string_answer = AnswerBox.get()
int_answer = int(string_answer)
回答by Pythonista
To get a value from an Entry widget in tkinter you call the get()
method on the widget. This will return the widget's value.
要从 tkinter 中的 Entry 小部件获取值,您可以调用get()
小部件上的方法。这将返回小部件的值。
So you would do answer = AnswerBox.get()
所以你会做 answer = AnswerBox.get()