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)]
csvfile.close()
root = Tk()
window=Window(root)
root.mainloop()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With