3

Here is my code:

import os
import tkinter as tk

from tkinter import filedialog

root = tk.Tk()

def click():
    folder = filedialog.askdirectory()
    button["text"] = folder

def click2():
    folder2 = filedialog.askdirectory()
    button1["text"] = folder2

def click3():
    list = os.listdir(folder)
    print(list)

entry = tk.Entry(root)
entry.grid(row=0, column=3)

label = tk.Label(root, text="Search from:")
label.grid(row=0, column=0)
label3 = tk.Label(root, text="Search:")
label3.grid(row=0, column=2)

label2 = tk.Label(root, text="Sort to:")
label2.grid(row=1, column = 0)

button = tk.Button(root, text="( ͡° ͜ʖ ͡°)", command=click, font=("TkDefaultFont", 12))
button.grid(row=0, column=1)

button1 = tk.Button(root, text="( ͡° ͜ʖ ͡°)", command=click2, font=("TkDefaultFont", 12))
button1.grid(row=1, column=1)

confirm = tk.Button(root, text="Confirm", command=click3, font=("TkDefaultFont", 12))
confirm.grid(row=2, column=1)


root.mainloop()

And I get an error: NameError: name 'folder' is not defined

As I understand, I need to somehow pass the "folder" variable between the two functions. I've already tried lots of things like using classes, that honestly, I'm not really familiar with.

Please help!

1 Answer 1

3

This is a classic problem when using functions. Within a function all the variables are local so they only exist in that function what you need to do is globalise the variable so that it exist throughout the program. This is done by saying global and then the variable name before defining said variable. Your new code should look like this.

global folder
folder = filedialog.askdirectory()
Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps you could add an explanation, for the benefit of the asker

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.