You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将tkinter的Text组件内容作为encrypt_file函数的参数传入?

问题解决办法

你的代码存在几个关键问题,以下是修复方案:

主要问题及修复:

  1. 缺少必要导入:需要导入 tkinter 和 cryptography 库中的 Fernet 类。如果尚未安装 cryptography,先运行 pip install cryptography。
  2. 未指定组件父窗口:所有 tkinter 组件(Text、Button)都需要绑定到一个根窗口(Tk 实例),否则会导致组件初始化失败。
  3. Lambda 语法错误:Button 的 command 参数里,encrypt_file 调用缺少闭合括号,直接引发语法错误。
  4. 密钥类型不匹配:Fernet 要求密钥为字节类型,需将字符串密钥转为 bytes 格式传入。
  5. 异常处理缺失:文件操作可能出现多种错误(如源文件不存在、路径无效、权限不足),添加异常捕获可避免程序直接崩溃并给出提示。

修复后的完整代码:

import tkinter
from cryptography.fernet import Fernet

# 创建根窗口
root = tkinter.Tk()
root.title("文件加密工具")
root.geometry("560x550")  # 设置窗口大小适配组件位置

# 文件路径输入框
text_first = tkinter.Text(
    root,  # 指定父窗口
    font='Arial 14',
)
text_first.place(x=20, y=150, height=33, width=520)
text_second = tkinter.Text(
    root,
    font='Arial 14',
)
text_second.place(x=20, y=275, height=33, width=520 )
text_third = tkinter.Text(
    root,
    font='Arial 14',
)
text_third.place(x=20, y=400, height=33, width=520)

# 加密函数
def encrypt_file_data(key, data):
    fn = Fernet(key)
    return fn.encrypt(data)

def encrypt_file(key, source, destination):
    try:
        with open(source, 'rb') as file:
            file_data = file.read()
            encrypted = encrypt_file_data(key, file_data)
        with open(destination, 'wb') as file:
            file.write(encrypted)
        # 加密成功后在第三个输入框提示
        text_third.delete('1.0', tkinter.END)
        text_third.insert('1.0', "文件加密完成!")
    except FileNotFoundError:
        text_third.delete('1.0', tkinter.END)
        text_third.insert('1.0', "错误:源文件不存在!")
    except Exception as e:
        text_third.delete('1.0', tkinter.END)
        text_third.insert('1.0', f"错误:{str(e)}")

# 加密按钮
tkinter.Button(
    root,
    text='生成加密文件',
    width=93,
    height=3,
    font=('Arial', 10, 'bold'),
    command=lambda: encrypt_file(
        b'M-Gx3UOPC2B8Xo6smM8MyMU51aP8aoKEyrz-ZkUdpOI=',  # 转为字节类型
        source=text_first.get('1.0', 'end-1c'), 
        destination=text_second.get('1.0', 'end-1c')
    )  # 补上缺失的闭合括号
).place(x=20, y=490)

root.mainloop()

使用说明:

  • 在第一个输入框输入源文件的完整路径(如 C:/test.txt)
  • 在第二个输入框输入加密后文件的保存路径(如 C:/test_encrypted.txt)
  • 点击按钮执行加密,结果会在第三个输入框显示

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 08:10:32