1

I use Tkinter as GUI library and i need to get list of files which i choose by calling askopenfilenames. Here is my function^

def choose_file(file_list)
    file_list = fd.askopenfilenames()
file_list = ()
b1 = Button(command = lambda: choose_file(file_list))

file_list - is variable in outer scope. But after calling function, this var is empty. What i did wrong?

2 Answers2

1

Try:

import tkinter.filedialog as fd
import tkinter as tk

def choose_file():
    global file_list
    file_list = fd.askopenfilenames()

file_list = ()
root = tk.Tk()
b1 = tk.Button(root, text="Click me", command=choose_file)
b1.pack()
root.mainloop()

The variable file_list is not global as it is immutable. To make it global you have to add global file_list to the start of your function definition. For more info read: Why you can change immutable if it's global.

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
TheLizzard
  • 7,248
  • 2
  • 11
  • 31
0

You have two different file_list variables in your code. One at global scope

file_list = ()

and one at function scope.

def choose_file(file_list):

With

    file_list = fd.askopenfilenames()

you are assigning the list returned by askopenfilenames to the function scope variable - everywhere in the function, file_list will have the list from askopenfilenames as value, what you can see by adding print(file_list) to your function twice, one time at the beginning and one time at the end.

To modify the global variable instead of the local one, you can either make the local (function scope) variable global

file_list = ()

def choose_file():
    global file_list
    file_list = fd.askopenfilenames()

b1 = Button(command = choose_file)

where the variable initialization must be moved before the function declaration (I think else it gives an UnboundLocalError or something), the lambda can be removed, and you do not need to pass file_list as an argument.

TheEagle
  • 5,808
  • 3
  • 11
  • 39