input() 语句不断引发类型错误



我创建了一个类,它使用PIL libraryImage模块中的一些方法/函数(我不知道该怎么称呼它们)。在此代码中,我要求用户输入要调整大小的图像的新高度。由于我希望用户在引发错误时再次输入它,因此我将其置于while循环中。

我最初试图接受一个元组,然后将其解压缩到new_height中并new_width变量,但我认为这可能会让用户感到困惑。

请假设所有导入都已完成。

class ImageManip:
def __init__(self):
    self.img_width, self.img_height = self.img.size
    self.img_resize()
def img_resize(self):
    while True:
        clear()
        try:
            img_new_width = input(
                'nnYour image's dimensions are:' +
                'nWidth: ' + self.img_width +
                'nHeight: ' + self.img_height +
                'nnEnter the width: '
            )
            img_new_height = input(
                'Enter the height: '
            )
        except TypeError:
            print('Oh no! You didn't enter a number! Try again.')
            time.sleep(2)
            print('nn', end='')
            continue
        else:
            self.img_final = self.img.thumbnail((img_new_width, img_new_height), Image.ANTIALIAS)
            self.img_final.show()
            break

System: Windows 10, 32bit Version: Python 3.6

input()需要用字符串调用。 self.img_heightself.img_width是代码中的整数。如果您调用这些str()将它们转换为字符串,它应该可以工作:

 img_new_width = input(
            'nnYour image's dimensions are:' +
            'nWidth: ' + str(self.img_width) +
            'nHeight: ' + str(self.img_height) +
            'nnEnter the width: '
        )

您可能还想使用 int() 将输入转换为整数:

img_new_width = int(input(
           ...
        )

相关内容

最新更新