I need help to understand why my python variable is not changing?
Here is the code:
from tkinter import filedialog
from tkinter import *
selectedRootFolder = "" #<-------------------------------------here is the variable declared
# get any folder to be a root folder
def add_dir():
root = Tk()
root.withdraw()
dirname = filedialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
selectedRootFolder = dirname
print("Here: " + selectedRootFolder)#<-----------------------here is the variable changed
# print the root folder
def print_root_dir_path():
print (selectedRootFolder) #<-----------------------------here is the variable empty -> =""
# in case a wrong number is taken
def invalid():
print("---------------------")
print ("INVALID CHOICE!")
print("---------------------")
# exit program
def exit_prog():
print ("Thank you, come back soon!")
exit()
# define the menu options
menu = {"1":("Choose Directory:", add_dir),
"2":("Print Root Directory Path",print_root_dir_path),
"9":("Exit",exit_prog)
}
while True:
# list the menu
for key in sorted(menu.keys()):
print (key + ":" + menu[key][0])
# pick a number
print("---------------------")
ans = input("Make A Choice: ")
print("---------------------")
#get the number, if none, call invalid function
menu.get(ans,[None,invalid])[1]()
This is just a part of the script, but it should be able to show my problem, which is that when I pick option 1, to choose a directory, it is successful, and it prints the selectedRootFolder, but when I choose option 2 after that, the printed value is just as declared in the beginning, empty.
I do not understand why is that, can u help me?
Thank you.
Edit 1:
Changed:
selectedRootFolder = print(dirname)
To:
selectedRootFolder = dirname
print("Here: " + selectedRootFolder)