Python程序关闭时出错
我希望你能再次帮助我,我仍然不懂编程,所以请容忍我。我得到了这个错误:Python程序关闭时出错,python,Python,我希望你能再次帮助我,我仍然不懂编程,所以请容忍我。我得到了这个错误: Traceback (most recent call last): File "C:\Python27\cx_Freeze exe Creator\Postcodezoekernl.py", line 136, in <module> postcodeinvoer = int(postcodeinvoer) TypeError: int() argument must be a string or
Traceback (most recent call last):
File "C:\Python27\cx_Freeze exe Creator\Postcodezoekernl.py", line 136, in <module>
postcodeinvoer = int(postcodeinvoer)
TypeError: int() argument must be a string or a number, not 'NoneType'
顺便问一下,是否可以将python文件编译为单个.exe文件?
希望你们能帮助我。提前谢谢
问题解决了 检查
postcodeinvoer
不是无
if postcodeinvoer:
postcodeinvoer = int(postcodeinvoer)
int(something)
将引发TypeError
或ValueError
,如果它可以从其参数实例化int,那么最简单的解决方案是捕获异常并重试。但是,由于我们希望允许用户取消该操作,我们仍然会重新测试None
,然后退出
cancel = False
basemsg = msg = "Voer een postcode in:"
while True:
postcodeinvoer = easygui.enterbox(msg=msg, title="Postcodezoeker")
if postcodeinvoer is None:
# user canceled
cancel = True
break
try:
postcodeinvoer = int(postcodeinvoer)
except (TypeError, ValueError) as e:
msg = "invalid value ! " + basemsg
else:
# ok, let's get out
break
if cancel:
# exit the program or whatever...
raise SysExit()
# ok, proceed with the user's value
现在你似乎犯了一个新手常见的错误,那就是认为如果某个东西是由数字组成的,那么它就是一个数字,事实并非如此。邮政编码或电话号码通常是字符串,而不是整数——问问自己,将电话号码乘以2并将结果除以邮政编码会有什么意义;)
因此,您根本不应该将postcodeinvoier
转换为int
。如果您所在的国家/地区的邮政编码仅由数字组成(并非所有国家/地区都是这样),则可以测试用户输入是否为由N
数字组成的字符串(根据您所在的国家/地区,N
的值):
但即使如此,这也可能不是一个足够好的验证 它将始终是
None
;它是小部件创建返回的值。他们必须检索小部件包含的值。@TigerhawkT3如果我正确理解文档,这可能不是真的,请参阅:返回:用户输入的文本,或者如果他取消操作,则不返回任何文本。
因此,在我看来,如果我正确理解问题中的情况,这实际上是一个正确的答案:当用户取消对话框时,postcodeinvoer
将具有None
作为其值,并且程序将因此错误而崩溃。显然,if条件在这种情况下会阻止这种情况的发生。首先,您希望针对None
进行明确的测试-因为在布尔测试中除了None
之外,还有其他东西的值为假-,然后您希望将int()
调用放入try/except块-因为有相当多的非None
int()
不会接受(非false)值。我已经用Surajano给我的答案修复了它。添加一个IF语句。编译后我发现了一个错误。如果我要发布完整的代码和cx\u freeze post的sutup.py,你能看一下吗?@MrJ。抱歉,这不是免费的“为我修复代码”这里的服务-您必须理解答案和代码示例,并自行修复自己的代码。当然,您可以自由发布有关“编译错误”的其他问题,但您可能需要确保问题(和解决方案)正确无误从错误消息/回溯中看不明显。好的,谢谢。我将尝试修复它,否则我将发布一个问题。再次感谢!
cancel = False
basemsg = msg = "Voer een postcode in:"
while True:
postcodeinvoer = easygui.enterbox(msg=msg, title="Postcodezoeker")
if postcodeinvoer is None:
# user canceled
cancel = True
break
try:
postcodeinvoer = int(postcodeinvoer)
except (TypeError, ValueError) as e:
msg = "invalid value ! " + basemsg
else:
# ok, let's get out
break
if cancel:
# exit the program or whatever...
raise SysExit()
# ok, proceed with the user's value
postcodeinvoer = easygui.enterbox(msg=msg, title="Postcodezoeker")
if postcodeinvoer is None:
# user canceled
cancel = True
break
if (postcodeinvoer.isdigit() and len(postcodeinvoer) == N):
# valid code
break
else:
# invalid code, ask again
msg = "invalid value ! " + basemsg