Retrieve multiple filenames via Tkinter - python

I am trying to build a simple app with Tkinter that can select multiple files and get their full path + filenames respectively.
Currently, the app can select multiple files but seems fail to get the full path, any pointer on this would be great.
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
import os
root = Tk()
root.geometry('200x100')
def browse():
filename = askopenfile(mode ='r', filetypes =[('files', '*.csv')], multiple=True)
pathlabel.config(text=filename)
browsebutton = Button(root, text="Browse", command=browse)
browsebutton.pack()
pathlabel = Label(root)
pathlabel.pack()
mainloop()

You can make use of the askopenfilename() instead of askopenfile() this will return a tuple containing the file paths of the files chosen. To obtain the file names, you can make use of the os.path.basename(file/path) this will return the corresponding file name (along with the extension). You can refer to the modified code below:
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfilename
import os
root = Tk()
def browse():
files = askopenfilename(filetypes =[('files', '*.csv')], multiple=True)
file_paths=''
file_names=''
for file in files:
file_paths+=file+'\n'
file_names+=os.path.basename(file)+'\n'
pathlabel.config(text=file_paths)
namelabel.config(text=file_names)
browsebutton = Button(root, text="Browse", command=browse)
browsebutton.pack()
path_head=Label(root,text='File Paths').pack()
pathlabel = Label(root)
pathlabel.pack()
name_head=Label(root,text='File Names').pack()
namelabel=Label(root)
namelabel.pack()
mainloop()

Related

How to get a user-selected file and feed it to a python program in Tkinter

I am currently messing about with Tkinter creating an interface for a project I created. The program takes in a bunch of file paths as inputs for it to run. I'm trying to create a tkinter interface where I can upload the 4 files I need or at least somehow get the filepaths and the. feed those to the program. Here is what I have:
import sys
import os
import comparatorclass
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
root=Tk()
root.geometry('1000x1000')
def open_file():
file = askopenfile(mode ='r', filetypes =[('Python Files', '*.py')])
if file is not None:
content = file.read()
print(content)
def run_comparator():
comparatorclass.main()
button2 = Button(root, text ='Open', command = lambda:open_file())
button2.pack(side = TOP, pady = 10)
button1 = Button(root,text="hello",command= run_comparator)
button1.pack()
root.mainloop()
as you can see, I have two buttons. The issue I'm having is how to connect my openfile function to my run_comparator function such that the 4 files I need to open are passed on to the run_comparator

How I used tkinter button to Import files

I would like to run a python program and when clicking a button in a (tkinter) window become import files form any direction and store it to another direction and in database .
import tkinter as tk
from tkinter import filedialog
def UploadAction(event=None):
filename = filedialog.askopenfilenames()
print('Selected:', filename)
root = tk.Tk()
button = tk.Button(root, text='import files', command=UploadAction)
button.grid(row=1,column=1,padx=10,pady=10)
root.mainloop()

Tkinter - Storing folder directory in function and calling it to change directory

I am trying to develop a GUI with tkinter. I have created a function (as a button) to browse for a directory folder ('input folder'). I have a routine linked to another button ('execute') that needs the path from 'input folder'.
I am getting errors when I try to pass the path from 'input folder' into os.chdir inside 'execute'. Example is as follows:
import sys
import os
from tkinter import filedialog
from tkinter import *
window = Tk()
def Input():
filename = filedialog.askdirectory()
global filename
def Extraction():
in_loc = filename
os.chdir(in_loc)
btn = Button(window, text="Extract", bg="black", fg="white", command=Extraction)
btn.pack()
btn2 = Button(text="Input", command=Input).pack()
window.mainloop()
Can anyone reproduce this and tell me what I am doing wrong here?
Thanks :)
Try this:
import sys
import os
from tkinter import filedialog
from tkinter import *
filename = ''
def input_function():
global filename
filename = filedialog.askdirectory()
def extraction():
global filename
in_loc = filename
os.chdir(in_loc)
window = Tk()
btn = Button(window, text="Extract", bg="black", fg="white", command=extraction)
btn.pack()
btn2 = Button(text="Input", command=input_function).pack()
window.mainloop()

askopenfilenames selecting multiple files

Using python 3.3 on a unix platform. I have seen many examples where the following code works but I am having an issue. When I select multiple files, I get an error message dialog box: "File /python/input_files/file1.txt file2.txt" does not exist. The error makes sense (tries to open a string of multiple files) but don't understand why others don't see it and how do I correct it. selectFiles is called via a button select. Appreciate any help.
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilenames
def selectFiles(self):
files = askopenfilenames(filetypes=(('Text files', '*.txt'),
('All files', '*.*')),
title='Select Input File'
)
fileList = root.tk.splitlist(files)
print('Files = ', fileList)
Here is the complete code:
#!/usr/local/bin/python3.3
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilenames
class multifilesApp(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
def initializeUI(self):
self.master.title('Select Files Application')
self.grid(row=0, column=0,sticky=W)
# Create the button to select files
self.button1 = Button(self.master, text='Select Files', command=self.selectFiles, width=10)
self.button1.grid(row=30, column=0)
def selectFiles(self):
files = askopenfilenames(filetypes=(('Text files', '*.txt'),
('All files', '*.*')),
title='Select Input File'
)
InputFileList = root.tk.splitlist(files)
print('Files = ', InputFileList)
# Begin Main
if __name__ == "__main__":
root = Tk()
root.minsize(width=250, height=400)
root.geometry("1200x800")
# Call the parser GUI application
app = multifilesApp(master=root)
app.initializeUI()
app.mainloop()
Maybe there is problem with Tcl/Tk on Sun4u
Try to run example in Tcl/Tk (example.tcl)
package require Tk
set filename [tk_getOpenFile -multiple true]
puts $filename
Run (probably):
tclsh example.tcl

Get a file's directory in a string selected by askopenfilename

I'm making a program that you use the askopenname file dialog to select a file, which I then want to save the directory to a string so I can use another function (which I already made) to extract the file to a different location that is predetermined.
My button code that opens the file dialog is this:
`a = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))`
This should be what you want:
import tkinter
import tkinter.filedialog
import getpass
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
# Get the file
file = tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user)
# Split the filepath to get the directory
directory = os.path.split(file)[0]
print(directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()
If you know where the file actually is, you could always just ask for a directory instead of the file using:
from tkFileDialog import askdirectory
directory= askdirectory()
Then in the code:
import tkinter
import tkinter.filedialog
import getpass
from tkFileDialog import askdirectory
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
directory= askdirectory()
print (directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()

Categories

Resources