Python 3.x ValueError:以10为基数的int()的文本无效-TextInput值
我最近开始学习Kivy,在处理文本输入框中输入的文本/数字时遇到了一个奇怪的错误 Kivy代码如下所示:Python 3.x ValueError:以10为基数的int()的文本无效-TextInput值,python-3.x,type-conversion,kivy,kivy-language,Python 3.x,Type Conversion,Kivy,Kivy Language,我最近开始学习Kivy,在处理文本输入框中输入的文本/数字时遇到了一个奇怪的错误 Kivy代码如下所示: BoxLayout: orientation: 'vertical' BoxLayout: orientation: 'horizontal' Label: text: 'No. of buttons:' markup: True
BoxLayout:
orientation: 'vertical'
BoxLayout:
orientation: 'horizontal'
Label:
text: 'No. of buttons:'
markup: True
color: 0, 0, 0, 1
CustomTextInput:
id: textinput_num
max_characters: 2
multiline: False
input_filter: 'int'
class DropDownScreen(Screen):
def add_dd_values(self):
dd_input = App.get_running_app().root.get_screen('dd_screen').ids.textinput_num.text
print("TextInputBox: ", dd_input, "\n")
print("Length: ",len(dd_input))
print(int(dd_input)+1)
相关Python代码如下所示:
BoxLayout:
orientation: 'vertical'
BoxLayout:
orientation: 'horizontal'
Label:
text: 'No. of buttons:'
markup: True
color: 0, 0, 0, 1
CustomTextInput:
id: textinput_num
max_characters: 2
multiline: False
input_filter: 'int'
class DropDownScreen(Screen):
def add_dd_values(self):
dd_input = App.get_running_app().root.get_screen('dd_screen').ids.textinput_num.text
print("TextInputBox: ", dd_input, "\n")
print("Length: ",len(dd_input))
print(int(dd_input)+1)
我引用了文本输入框的值,如下所示:
dd_input = App.get_running_app().root.get_screen('dd_screen').ids.textinput_num.text
这里,textinput_num是相关文本输入框的id。我可以打印文本输入框的值,还可以检查字符串的长度。注意:我使用了input_filter:'int'语句只允许文本输入框中的数字。我理解dd_输入将接收字符串值。所以,我试着把它转换成一个整数值,然后执行一个数值运算
但是,我得到了以下错误:ValueError:int()的文本无效,以10为基数:
我在谷歌上查到,这似乎是处理数据类型的问题
你能帮我理解这里出了什么问题吗?从文本输入框中访问和读取数值的正确方法是什么
最奇怪的是,对于同一段代码,这种错误本质上是间歇性的。有时返回错误,有时不返回。您提到错误是“间歇性的”。我可能错了,但我认为这就是正在发生的事情。当textinput字段为空/空白时,将出现异常/错误。本质上,这意味着dd_输入的值为null,或者它指向一个不能转换为整数的空字符串。因此,出现了错误 添加一个条件来处理异常并查看发生了什么:
if dd_input == '':
dd_input="0"
您忽略了错误消息中最有趣的部分:以10为基数的int()的无效文本是什么?@mkrieger1很抱歉没有看到。我输入了11或12作为输入。请显示您在本例中得到的准确完整的错误消息。@mkrieger1我以为我输入的是11或12,但重新检查问题时指出了明显的错误:ValueError:以10为基数的int()的文本无效:“”。它是一个null或空字符串。很抱歉问了这么愚蠢的问题。我本应该更小心的,就是这样。非常感谢。这真是个愚蠢的错误。