I am running a simple python script that opens a window with a button inside of it. When the user clicks the button a dialog box opens and asks the user to select a file directory. I want to pull that directory location out of the function. This is what the code looks like:
from tkinter import *
from tkinter import filedialog
def openFile():
filePath= filedialog.askdirectory()
return filePath
window = Tk()
button = Button(text="open", command=openFile)
button.pack()
window.mainloop()
I would like the file directory to be saved in a variable inside the window. I am able to print the filepath inside the function but I am unable to bring it out of the function.
Any help will be greatly appreciated
You cannot use the return value for functions added to buttons, as there is no way of picking up whatever is returned.
So instead you can write the return to a global variable, or a class variable, instead. Example with global variable below;
from tkinter import *
from tkinter import filedialog
my_path = None
def openFile():
global my_path
filePath = filedialog.askdirectory()
my_path = filePath
window = Tk()
button = Button(text="open", command=openFile)
button.pack()
window.mainloop()
You will then be able to pick up the my_path variable later in your script after clicking the button.
Related
When I run my code, I can get any file filepath for further use and put it in the Entry box. When I try to get a filepath of a shortcut, another window opens up, saying "catastrophic error". The console remains quiet all the time. Here's my code:
from tkinter import *
from PIL import *
import os
from tkinter import filedialog
root = Tk()
def create_game():
# Defining the function for choosing the filepath
def add_data():
root.filename = filedialog.askopenfilename(initialdir="",title="Select A File",filetypes=((".EXE files", "*.exe"),("all", "*.*")))
enter_filepath.insert(0,str(root.filename))
enter_filepath = Entry(root,width=30)
enter_filepath.pack()
btn_filepath = Button(root,text="Choose file",command=add_data)
btn_filepath.pack()
create_game()
root.mainloop()
This is what I'm getting:
I am trying to restart my main GUI/Halt the program flow when I Click on the "X" button in my tkinter messagebox . Any idea how can I do this ?
PS: I have read the many threads about closing the main GUI itself but nothing specific to messagebox
By default , my code proceeds to ask me for an output path using the filedailog.askdirectory() method when clicking "ok", or on closing the messagebox
My message box and the main GUI in the background
There's no simple way to add a custom handler to the "X" button. I think it's better to use messagebox.askokcancel() variation of messageboxes instead of showinfo, and halt the program if the returned result is False:
import tkinter as tk
from tkinter import messagebox, filedialog
root = tk.Tk()
def show_messagebox():
result = messagebox.askokcancel("Output path", "Please select an output file path")
if result:
filedialog.askdirectory()
else:
messagebox.showinfo("Program is halted")
tk.Button(root, text="Show messagebox", command=show_messagebox).pack()
root.mainloop()
Or, even simpler, you can just show filedialog.askdirectory() directly. If the user doesn't want to choose directory, they can click on the "Cancel" button, and then the program checks if there was empty value returned, and halts if so:
import tkinter as tk
from tkinter import messagebox, filedialog
root = tk.Tk()
def show_askdirectory():
directory = filedialog.askdirectory(title="Please select an output file path")
if not directory:
messagebox.showinfo(message="The program is halted")
else:
messagebox.showinfo(message="Chosen directory: " + directory)
tk.Button(root, text="Choose directory", command=show_askdirectory).pack()
root.mainloop()
I'm using tkinter. And I am trying to get a file path from a button and use it as an input for an other function. I defined filepathforinfo as a global variable, but I am not getting the expected result.
I tried to follow the solution here.
Here is the main part of the code:
import tkinter.filedialog
import tkinter as tk
def get_pdf_file():
global filepathforinfo #can be avoided by using classes
filetypes=[('PDF files', '*.pdf')]
filepathforinfo = tk.filedialog.askopenfilename( title='Open a file',initialdir='/', filetypes=filetypes)
filepathforinfo='test'
# Toplevel object which will
# be treated as a new window
Information_Window = tk.Tk()
Information_Window.title("Information extraction")
Information_Window.resizable(True, True)
Information_Window['background']='#8c52ff'
info_button = tk.Button(Information_Window, text="Give the pdf file to extract information from", activebackground='purple',activeforeground='purple' ,command=get_pdf_file)
info_button.grid(row=0,column=0)
print(filepathforinfo)
#get_pdf_info(filepathforinfo)
Information_Window.mainloop()
After clicking the button and choosing the file, I get as an output only this :
Out[1]: 'test'
I dont know why I dont get the file path.
The closest answer I got is here, but it is still not satisfying.
The problem is your printing filepathforinfo before its even changed. I created a label to show it as it actually works.
import tkinter.filedialog
import tkinter as tk
def get_pdf_file():
global filepathforinfo
filetypes=[('PDF files', '*.pdf')]
filepathforinfo = tk.filedialog.askopenfilename( title='Open a file',initialdir='/', filetypes=filetypes)
info_label['text'] = filepathforinfo
filepathforinfo='test'
# Toplevel object which will
# be treated as a new window
Information_Window = tk.Tk()
Information_Window.title("Information extraction")
Information_Window.resizable(True, True)
Information_Window['background']='#8c52ff'
info_button = tk.Button(Information_Window, text="Give the pdf file to extract information from", activebackground='purple',activeforeground='purple' ,command=get_pdf_file)
info_button.grid(row=0,column=0)
info_label = tk.Label(Information_Window, text= filepathforinfo)
info_label.grid()
Information_Window.mainloop()
We're trying to store a directory path in a variable using Tkinter's tkFileDialog, and it won't work (details later).
from Tkinter import *
import os
from tkFileDialog import askopenfilename, askdirectory
# Create the window
root = Tk()
# Application title & size
root.title("Title")
root.geometry("1000x600")
# Creating frame to add things to
app = Frame(root)
app.grid() # Adding app frame to grid
# Method that opens file chooser
# Gets used when button is clicked (command)
def openFileBox():
directoryPicked = tkFileDialog.askdirectory()
#easygui.fileopenbox()
for filePicked in os.listdir(directoryPicked):
if filePicked.lower().endswith(".jpg") or filePicked.lower().endswith(".gif") or filePicked.lower().endswith(".png"):
print filePicked
#TODO: add button 'Select Folder'
loaderButton = Button(app)
loaderButton["text"] = "Select Folder"
loaderButton["command"] = openFileBox
loaderButton.grid()
# Tells the program to run everything above
root.mainloop()
So what needs to happen? The way we see it (and we're beginners looking for feedback here), it should be running the openFileBox method when the button is pressed. When the method runs, it should store a selected directory to directoryPicked and print it to the console just to be sure it's working, but when we press the button it simply says 'tkFileDialog' is not defined.
Any thoughts?
It's because you're only importing askopenfilename, askdirectory from tkFileDialog you're not actually importing tkFileDialog itself
So you need to change directoryPicked = tkFileDialog.askdirectory() to directoryPicked = askdirectory()
trying to make a GUI with an 'open file' button. When I run the code shown below, the open file dialog opens straight away, and not when I press the button. Why? Is there a simple way to fix this that doesn't involve using classes? (I don't currently know anything about classes and am working on a time-pressured project)
from tkinter import *
interface = Tk()
def openfile():
return filedialog.askopenfilename()
button = ttk.Button(interface, text = "Open", command = openfile())
button.grid(column = 1, row = 1)
interface.mainloop()
The code is passing the return value of the openfile function call, not the function itself. Pass the function itself by removing trailing () which cause a call.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
interface = Tk()
def openfile():
return filedialog.askopenfilename()
button = ttk.Button(interface, text="Open", command=openfile) # <------
button.grid(column=1, row=1)
interface.mainloop()