8

I'm writing some code where the user needs to be able to select a file that the program will run on. I have created a browse button that allows the user to select a file but when you hit 'okay' the rest of the program doesn't realize that there has been an input. The file name should also automatically be entered in he browse bar after the file has been selected. Any suggestions?

from Tkinter import *

class Window:       

def __init__(self, master):     
    
    #Browse Bar
    csvfile=Label(root, text="File").grid(row=1, column=0)
    bar = Entry(master).grid(row=1, column=1) 
    
    #Buttons  
    y = 7
    self.cbutton= Button(root, text="OK", command=master.destroy)       #closes window
    y += 1
    self.cbutton.grid(row=10, column=3, sticky = W + E)
    self.bbutton= Button(root, text="Browse", command=self.browsecsv)
    self.bbutton.grid(row=1, column=3)
                     
#-------------------------------------------------------------------------------------#
def browsecsv(self):
    from tkFileDialog import askopenfilename

    Tk().withdraw() 
    filename = askopenfilename()
    
#-------------------------------------------------------------------------------------#
import csv

with open('filename', 'rb') as csvfile:
    logreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    rownum = 0
    
    for row in logreader:    
        NumColumns = len(row)        
        rownum += 1
        
    Matrix = [[0 for x in xrange(NumColumns)] for x in xrange(rownum)] 
      

root = Tk()
window = Window(root)
root.mainloop()  
1
  • this is an old post and answers based on import tkFileDialog are supported for Python2. See this post for details Commented Oct 17, 2024 at 16:13

5 Answers 5

6

you can also use tkFileDialog..

import Tkinter,tkFileDialog

root = Tkinter.Tk()
file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file')
if file:
    data = file.read()
    file.close()
    print "I got %d bytes from this file." % len(data)
Sign up to request clarification or add additional context in comments.

Comments

4

filename = askopenfilename() is only known in this scope, you have to return it or use it in any way.

See this site for more examples:

    Tkinter.Button(self, text='Browse', command=self.askopenfile)

...

    def askopenfile(self):
        return tkFileDialog.askopenfile(mode='r', **self.file_opt)

EDIT

Bryan Oakley is right of course! That is what I meant when i said "use it in any way" ;) At one point you choose a filename, at anoter you simply use filename.

How about this?

from Tkinter import *
import csv

class Window:       
def __init__(self, master):     
    self.filename=""
    csvfile=Label(root, text="File").grid(row=1, column=0)
    bar=Entry(master).grid(row=1, column=1) 

    #Buttons  
    y=7
    self.cbutton= Button(root, text="OK", command=self.process_csv)
    y+=1
    self.cbutton.grid(row=10, column=3, sticky = W + E)
    self.bbutton= Button(root, text="Browse", command=self.browsecsv)
    self.bbutton.grid(row=1, column=3)

def browsecsv(self):
    from tkFileDialog import askopenfilename

    Tk().withdraw() 
    self.filename = askopenfilename()

def process_csv(self):
    if self.filename:
        with open(self.filename, 'rb') as csvfile:
            logreader = csv.reader(csvfile, delimiter=',', quotechar='|')
            rownum=0

            for row in logreader:    
                NumColumns = len(row)        
                rownum += 1

            Matrix = [[0 for x in xrange(NumColumns)] for x in xrange(rownum)] 

root = Tk()
window=Window(root)
root.mainloop()  

There is still a lot to do with that, but at least you don't try to open a file before having determined its name.

2 Comments

this isn't the core problem. The problem is that the code is trying to process the csv file before the GUI even starts up. The code that is processing the file needs to be moved to a function, and called after the file dialog is closed.
does Tkinter have the capability to take the filepath from a filedialogbox (eg: C:\textfile.txt) and put it into an Entry box?
4
# importing tkinter and tkinter.ttk 
# and all their functions and classes 
from tkinter import * 
from tkinter.ttk import *

# importing askopenfile function 
# from class filedialog 
from tkinter.filedialog import askopenfile 


root = Tk() 
root.geometry('200x100') 

# This function will be used to open 
# file in read mode and only Python files 
# will be opened 
def open_file(): 
    file = askopenfile(
        mode='r',
        initialdir='~',
        title="Select docx-file",
        filetypes=[('Python Files', '*.docx')]
    )

    if file is not None:
        # file supports the descriptor protocol
        content = file.read() 
        print(content)
        file.close()


btn = Button(root, text='Open', command=open_file) 
btn.pack(side=TOP, pady=10) 

mainloop()

tkinter.filedialog.askopenfile is wrapper of the class tkinter.filedialog.Open.

tkinter.filedialog.Open is a child class of tkinter.filedialog._Dialog which itself is a child of tkinter.commondialog.Dialog.

All these are written in pure Python so the source code is accessible via inspect.getsource.

3 Comments

Welcome to stackoverflow. In addition to the answer you've provided, please consider providing a brief explanation of why and how this fixes the issue.
This was the first example that actually worked, thanks! I did change the '*.docx' to see all files :) cant write how.
to hide hidden files check this
2

The root of the problem is that you're trying to process the file before the user has the chance to pick a file.

You need to put the block of code beginning with with open('filename', 'rb') as csvfile: in a function, then call the function as a result of the user pressing the button. For example, you could call it from within the browsecsv function.

Also, you don't need csv.close(), that comes for free when using the with statement.

Comments

-1

I have edited above code to use in python 3.6. Only package name changes

    import tkinter
    from tkinter import filedialog
    file = filedialog.askopenfile(parent=root,mode='rb',title='Choose a file')
    if file != None:
        data = file.read()
        file.close()
        print("I got %d bytes from this file." % len(data))

2 Comments

it gives error. root is not defined
see answer of Iftikhar humayun for the proper implementation of this approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.