Ollie
Ollie

Reputation: 117

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.

Upvotes: 1

Views: 1637

Answers (2)

Kardi Teknomo
Kardi Teknomo

Reputation: 1460

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

Upvotes: 1

Anteino
Anteino

Reputation: 1156

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.

Upvotes: 2

Related Questions