简体   繁体   中英

Refer to a variable inside another function in Python

The intention is to have a user choose a file via

select_file_en

which will then be encrypted via

encrypt

I want the program to save the filename of the chosen file in a variable, which can be accessed by the encryption part. I'm a newbie so please bare with me if this is easy to fix. Code can be found at https://github.com/KDropZ/NDA/blob/main/main.py and is by far not final at all. When I run the encrypt part I get the following Error, so my way to "call" the variable seems to be wrong I guess?

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'

Additional info: Python 3.8.10, Tkinter 8.6, Ubuntu OS

Code example


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)

the problem is in line 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')

You call the encrypt(filename) function on a button click ( command=encrypt ), but you do not provide the filename: This is also what your error message says: missing 1 required positional argument: 'filename' .

You need to find a way to provide the function in the tkinter button with a variable: look here.

basically, you need to save the filename that is chosen in select_file_en() to a variable (lets call it my_filename ), and then use a lambda function (ELI5: a small function, often used in another function) to pass the variable in the command used in the tkinter button:

command= lambda: encrypt(my_filename)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM