我想在输入EntryText小部件后显示字符串和整数值。
我在代码下使用并且能够显示整数值但不能显示字符串:
global Input
Input = int(entrytext1.get())
print Input
如果我在entrytext1中输入'q',请输入以下错误:
ValueError: invalid literal for int() with base 10: 'q'
如果我使用下面的代码,则会出现以下错误:
global Input
Input = (entrytext1.get())
print Input
No_SED_MENU_Items = len(SED_MENU_Items)
print No_SED_MENU_Items
if (not((Input > 0 ) and (Input <= No_SED_MENU_Items))):
print('\nInvalid option')
else:
SMI = SED_MENU_Items[Input-1]['ID']
SED_item_select = hex(SMI)[2:].zfill(4)
FirstByte = SED_item_select[0:2]
SecByte = SED_item_select[2:4]
request = '22'+ ' '+FirstByte+' '+SecByte
print (request)
错误:
UnboundLocalError: local variable 'request' referenced before assignment
如何解决这个问题,如果我输入整数,它应该打印我的请求,如果我输入字符串,如果只打印
答案 0 :(得分:0)
您可以将Input
更改为接受输入而不立即强制转换,但稍后会根据您要对它们执行的操作进行转换。这就是你如何做到的。
Input = (entrytext1.get()) #Remove the integer casting
print (str(Input)) #Converts 'Input' to a string
print (int(Input)) #Converts 'Input' to an integer
问题在于Input
期待任何数据类型,因为没有验证。通过删除数据类型并在以后进行转换,您可以输入任何内容。这可能会导致问题,因为如果您尝试将ValueError
转换为整数,Python将返回'q'
。
要完成此操作,您可以使用try-except
块。从对OP的评论来看,这个解决方案更适合你,因为它允许整数和字符串输入,但只有在可能时才进行强制转换,从而消除了出错的可能性。我在下面的示例函数中实现了这个。
def CastIfPossible():
Input = (entrytext1.get())
try: #Try converting the input to an integer
cast_test = int(Input)
return cast_test #Returns if it is possible
except ValueError: #If it is not possible
print ("That was a string, not an integer. Casting is not possible.")
return Input #Return the original input as a string
if __name__ == "__main__":
cast_value = CastIfPossible()
print (cast_value) #Prints both int and str inputs
这允许用户输入任何内容,如果可能,将其转换为整数,如果不允许,则将其保留为字符串。