首页 > 解决方案 > 显示 ValueError:int() 以 10 为基数的无效文字:'\n'

问题描述

在这里,我正在制作一个对图像进行加密的项目,当我运行代码时,它显示 ValueError: invalid literal for int() with base 10: '\n'

我的代码:

from tkinter import Tk
from tkinter import *
from tkinter import filedialog
def encript():
    root = Tk()
    root.geometry("200x160")
    def encript_image():
        file1 = filedialog.askopenfile(mode='r', filetype=[('jpg file', '*.jpg')])
        if file1 is not None:
            # print(file1)
            file_name = file1.name
            # print(file_name)
            key = entry1.get(1.0, END)
            print(file_name, key)
            fi = open(file_name, 'rb')
            image = fi.read()
            fi.close()
            image = bytearray(image)
            for index, value in enumerate(image):
                image[index] = value^int(key)
            fi1 = open(file_name, 'wb')
            fi1.write(image)
            fi1.close()


    b1 = Button(root, text="encript", command=encript_image)
    b1.place(x=70, y=20)
    entry1 = Text(root, height=1, width=10)

    entry1.place(x=50, y=50)

    root.mainloop()
encript()

在运行此代码时出现错误:

ValueError: invalid literal for int() with base 10: '\n'

我不知道我必须在这做什么

标签: pythonpython-3.xpython-2.7

解决方案


好吧,错误表明 '\n' 不是有效的文字,因为 '\n' 不是整数。从提供的代码来看,我看到您正在尝试使用指定密钥使用 XOR 加密(^ 符号)来加密图像。为此,您尝试获取 ASCII 字符的整数版本,但是您使用的是 int(),它将字符串文字中的整数转换为可用的整数。

x = int(“12”)
print(x) # Prints the integer 12

要获取 ASCII 字符的整数版本,请使用 ord()

x = ord(‘a’)
print(x) # Prints the integer 97

推荐阅读