I'm making a project in which I have to implement a browse folder button and further put that file path into another function. I made a function that asks me for the directory and it returns the path. but the problem I am facing is whenever I'm calling the function the window also opens for me to select the path again. how can I store the path in a variable without triggering the askdirectory() function?
Here is my code :
from tkinter import *
from tkinter import filedialog
import tkinter as tk
full = tk.Tk()
full.geometry("400x200")
name = Label(full, text = "Enter Image Directory").place(x = 5,y = 30)
def askDir():
file = filedialog.askdirectory()
return file
dir = askDir() # doing this will always trigger the askdirectory function.
print (dir)
Button(full,text = "Browse",command = lambda:askDir(),padx=50).place(x = 140, y = 30)
# i only want the function to be triggered when i press the button
full.mainloop()
My expectation is when ill press the button then only ill get the select directory prompt and after selecting the path should get stored in a variable that I can use in another function.
CodePudding user response:
use code below:
from tkinter import *
from tkinter import filedialog
import tkinter as tk
full = tk.Tk()
full.geometry("400x200")
name = Label(full, text = "Enter Image Directory").place(x = 5,y = 30)
dir=None
def askDir():
global dir
dir = filedialog.askdirectory()
test()
def test():
print(dir)
Button(full,text = "Browse",command = lambda:askDir(),padx=50).place(x = 140, y = 30)
full.mainloop()
just define (dir) as a global variable. now you can use (dir) in any function that you want.
have fun :)