目的是讓用戶通過
select_file_en
然后將通過
encrypt
我希望程式將所選檔案的檔案名保存在一個變數中,加密部分可以訪問該變數。我是新手,所以如果這很容易解決,請與我裸露。代碼可以在https://github.com/KDropZ/NDA/blob/main/main.py找到,到目前為止還不是最終的。當我運行加密部分時,我得到以下錯誤,所以我猜我“呼叫”變數的方式似乎是錯誤的?
Exception in Tkinter callback Traceback (most recent call last):
File "/usr/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args) TypeError: encrypt() missing 1 required positional argument: 'filename'
附加資訊:Python 3.8.10、Tkinter 8.6、Ubuntu 作業系統
代碼示例
import tkinter as tk
from tkinter import ttk
import tkinter.font as font
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
import os
def select_file_en():
filetypes = (
('All files', '*.*'),
)
filename = fd.askopenfilename(
title='Choose a file to encrypt',
initialdir='/',
filetypes=filetypes)
showinfo(
title='Selected File',
message=filename
)
def encrypt(filename):
to_encrypt = open(filename, "rb").read()
size = len(to_encrypt)
key = os.urandom(size)
with open(filename ".key", "wb") as key_out:
key_out.write(key)
encrypted = bytes(a^b for (a,b) in zip(filename, key))
with open(filename, "wb") as encrypted_out:
encrypted_out.write(encrypted)
編輯:解決了!
我同時使用了全域變數和 lambda 來解決這個問題。一切都像魅力一樣,感謝您的幫助!<3
uj5u.com熱心網友回復:
問題在第 127 行:
tk.Button(root, cursor='hand2', text='Encrypt file', font=buttonFont, bg='#FF6D6D', fg='#ffffff', command=encrypt).place(anchor='nw', relx='0.78', rely='0.12', x='0', y='0')
encrypt(filename)您在按鈕單擊 ( ) 時呼叫該函式command=encrypt,但您沒有提供檔案名!這也是您的錯誤訊息所說的:missing 1 required positional argument: 'filename'。
您需要找到一種方法來為 tkinter 按鈕中的函式提供變數:看這里。
基本上,您需要將選擇的檔案名保存select_file_en()到一個變數中(讓我們呼叫它my_filename),然后使用一個lambda函式(ELI5:一個小函式,通常在另一個函式中使用)在 tkinter 中使用的命令中傳遞變數按鈕:
command= lambda: encrypt(my_filename)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/456970.html
上一篇:如何檢查頂層視窗是否打開?
