[英]How to get an integer from a tkinter entry box?
I am trying to work out how to get a value from a tkinter entry box, and then store it as a integer.我正在尝试解决如何从 tkinter 输入框中获取值,然后将其存储为整数。 This is what I have:这就是我所拥有的:
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".我想从 AnswerBox 获取然后输入,并将其存储在整数变量“answer”中。 How can I do this?我怎样才能做到这一点?
Thanks谢谢
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
方法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)
To get a value from an Entry widget in tkinter you call the get()
method on the widget.要从 tkinter 中的 Entry 小部件获取值,您可以调用小部件上的get()
方法。 This will return the widget's value.这将返回小部件的值。
So you would do answer = AnswerBox.get()
所以你会做answer = AnswerBox.get()
I have Done the same thing But it gives the following error. 我做过同样的事情,但是会出现以下错误。
Traceback (most recent call last):
File "G:/Coding/Python/first-hit/Mangal's CAFE.py", line 228, in <module>
print(int(x))
ValueError: invalid literal for int() with base 10: ''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.