Get the file path in global variable from browse button with tkinter - python

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()

Related

Getting file directory from tkinter function

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.

Open a specific file from a tkinter window

I have a tkinter window and need to press a button to open a csv file. For example:
root = Tk()
def open_file():
# show the csv file to the user
open_button = Button(root, text="Open", command=open_file)
open_button.pack()
Is there a way to do this, or something similar? I have tried using askopenfilename, but this doesn't seem to work for me, as it only opens the home directory.
Have a look at this link. As you can see from the link, the approaches differ a bit for python 2.7 and 3. Since python 2.7 is reaching the end of its life, I will demonstrate for python 3:
from tkinter import filedialog
from tkinter import *
root = Tk()
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
If you correctly installed tkinter using pip and filled all the arguments correctly it should work. Make sure the root directory actually exists and you specified syntactically correct (types of slashes matter).
You can also open the file picker even though it starts in the wrong directory. You can browse to the correct root directory and click ok and have the program print the directory. Then you'll know how to specify the root directory.
The following code show tkinter window with a button. When the user click the button and point to a CSV file, it would show the first few lines into a message box for show. I use pandas to open the CSV file.
import tkinter as tk
from tkinter import filedialog
import tkinter.messagebox as msgBox
import os
import pandas as pd
def open_file():
filename = filedialog.askopenfilename(initialdir=os.getcwd())
if(filename!=''):
df = pd.read_csv(filename, encoding = "ISO-8859-1", low_memory=False)
mR,mC=df.shape
cols = df.columns
num=5
pd.options.display.float_format = '{:.2f}'.format
msg=str(df.iloc[:num,:]) + '\n' + '...\n' + \
df.iloc[-num:,:].to_string(header=False) + '\n\n' + \
str(df.describe())
msgBox.showinfo(title="Data", message=msg)
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame, text="Open", command=open_file)
button.pack(side = tk.LEFT)
root.mainloop()

Python Tkinter - cannot select directory (tkFileDialog not found)

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()

Redirect my console output to my Tkinter text area widget

I'm a newbie on tkinter, my code can run but I need my text widget to display only the result variable in the callback() function not including the 'askopenfilename' method.
from Tkinter import *
from tkFileDialog import *
import os
root = Tk()
root.geometry('900x700')
path = StringVar()
#browse pdf files
def callback():
f = askopenfilename(title='Open Files',initialdir='C:\Users\shantini\Desktop\PDF',
filetypes=[('Files of type:','*.PDF'),('Files of type:','*.pdf')])
path.set(f)
result = os.popen('pdfid.py'+' '+f).read()
return result
#labelframe(text pdf output)
label=LabelFrame(root, text="PDF Analysis Output")
label.pack(side=BOTTOM, anchor=W, fill=BOTH, expand=YES)
text = Text(label,bg='white')
text.pack(fill=BOTH, expand=YES)
text.insert(INSERT,callback())
root.mainloop()
If you disable Text widget, you make it read-only, so you cant add text to it. So to add text, make it normal, or remove the state parameter. I changed your callback to reflect the comments:
def callback():
f = askopenfilename(title='Open Files',initialdir='/tmp',
filetypes=[('Files of type:','*.PDF'),('Files of type:','*.pdf')])
result = open(f).read() # I also changed this as I dont have `pdfid.py` to test the code
text_area.insert(INSERT, result)
print result
I slightly change the input files and folder, as I work in linux and cant use windows paths. Hope this helps.

Simplest way to open a file in tkinter

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()

Categories