This GUI allows the user to open the file browser and select the files you need, show it on the field blank and then open the file once open is pressed. I'm new to python and had tried placing print tkFileDialog.askopenfilename() at the self.filename but this results in a syntax error. Please help. Thanks!
My question is as follows: 1) Why does my file browser open twice upon pressing the "file browser" button. 2) Also, how do I state the directory of the file selected in the file blank instead of in the python command prompt?
I would like to open the file in the future after pressing the ok button.
from Tkinter import *
import csv
import tkFileDialog
class Window:
def __init__(self, master):
self.filename=""
csvfile=Label(root, text="Load File:").grid(row=1, column=0)
bar=Entry(master).grid(row=1, column=1)
#Buttons
y=12
self.cbutton= Button(root, text="OK", command=self.process_csv) #command refer to process_csv
y+=1
self.cbutton.grid(row=15, column=3, sticky = W + E)
self.bbutton= Button(root, text="File Browser", command=self.browsecsv) #open browser; refer to browsecsv
self.bbutton.grid(row=1, column=3)
def browsecsv(self):
from tkFileDialog import askopenfilename
Tk().withdraw()
self.filename = askopenfilename()
print tkFileDialog.askopenfilename() # print the file that you opened.
def callback():
abc = askopenfilename()
execfile("input.xlsx")
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()
Your both questions are connected. The problem is in your browsecsv(self)
method. Your directory
is already stored in self.filename
, no need to call askopenfilename()
again. That's the reason why the file browser opens twice. Moreover, to set text in your Entry
, you need to assign it a text variable.
self.entryText = StringVar()
self.bar = Entry(root, textvariable=self.entryText ).grid(row=1, column=1)
Then, you can assign it to the Entry
in your method:
def browsecsv(self):
from tkFileDialog import askopenfilename
Tk().withdraw()
self.filename = askopenfilename()
self.entryText.set(self.filename)