Search code examples
pythonpython-3.xtkinterglobal-variables

Can't make folder_path = filedialog.askdirectory() global


I don't know why but even if I declare the variable folder_path as global in the function, if I print it outside of it the value doesn't change....

This is the code

import cv2
import pytesseract
import os
import tkinter as tk
from tkinter import filedialog

pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'

class images():
    def __init__(self,path):
        self.path = path
        self.cv = cv2.imread(self.path)

folder_path = 'if u see this after selecting a folder the global isnt working'
def browseButton():
    global folder_path
    folder_path = filedialog.askdirectory()

def newfunc():
    print(folder_path)


#-----------------------------------GUI---------------------------------------------------

window = tk.Tk()
window.geometry('600x400')
window.title('Text scanner')
window.resizable(False,False)


bg = tk.Canvas(window, bg="#ebba34", width='590', height='390')
intro_label = tk.Label(window,
text="Benvenuto nel Text Scanner, seleziona il percorso file dove hai inserito le immagini.",
font=("Helvetica", 9))
file_path_entry = tk.Entry()
file_path_button = tk.Button(cursor='hand2', text='Browse', command=browseButton) 

bg.pack()
intro_label.place(x=68,y=20)
file_path_entry.place(x=17,y=50, width=513)
file_path_button.place(x=533,y=50,height=20, width=50)



#-----------------------------------MAIN LOOP-----------------------------------------
if __name__ == '__main__':
    window.mainloop()
newfunc()

Now I don't get anything in output until I close the program

However if I put the print inside the function it outputs the folder_path correctly but I need it outside of it to use it into another function (which I cannot combine with this one)


Solution

  • Your folder_path wont change as long as browseButton() is not executed, hence keeping it in the main block of the code wont change the path, instead you should keep it inside a function like you presumed.

    However if I put the print inside the function it outputs the folder_path correctly but I need it outside of it to use it into another function (which I cannot combine with this one)

    This in any situation is not needed, you can create a new function wherever you want and use folder_path inside of that. As long as browseButton() has been executed, folder_path will be assigned with the new value.

    def new_func():
        print(folder_path) # New path will be printed
    

    In other words, you are printing folder_path right after defining it as 'if u see this after selecting a folder the global isnt working', the function that changes its definition does not get a chance to get executed or change the value of the variable, hence you should move print(folder_path) inside other function that runs only AFTER browseButton() has been executed.