0

So I have something like this:

import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import pandas as pd

window = tk.Tk()
window.geometry('350x240')

def open_file():
    temp_file = filedialog.askopenfilename(title="Open file", filetypes=[("Excel files", "*.csv")])
    temp_file = open(temp_file, "r")
    Proj_df = pd.read_csv(temp_file)

open_button = ttk.Button(text='Select File...', command=open_file)
open_button.grid(column=1, row=1)

def get_info():
    x = open_button.get()
    print (x)

button1 = ttk.Button(text='Get Information', command=get_info)

button1.grid(column=0, row=2)

What I'm trying to do is to store the DataFrame created in open_file() to use it in get_info(). I'm getting:

AttributeError: 'Button' object has no attribute 'get'

How could I access the DataFrame created in open_button?

1
  • make it global, there is really no way to retrieve values from functions that are called by a Button from that Button (I mean it is not impossible to create a button that would be able to do this, but it is much easier to just use global (or OOP)) Commented Dec 29, 2021 at 14:02

1 Answer 1

2

This might help you along the way. You can set a tk.StringVar then use to retrieve, store, and access items that are input through various tk/ttk widgets. Also I suppose you might want to store your inbound file? I ran this attempt simply reading in the csv, not using pandas.

import tkinter as tk
from tkinter import filedialog, ttk
#import pandas as pd

window = tk.Tk()
window.geometry('350x240')
tkvar1 = tk.StringVar(window)

def open_file():
    temp_file = filedialog.askopenfilename(title="Open file", filetypes=[("Excel files", "*.csv")])
    temp_file = open(temp_file, "r")
    tkvar1.set(temp_file.read())
    #Proj_df = pd.read_csv(temp_file)

open_button = ttk.Button(text='Select File...', command=open_file)
open_button.grid(column=1, row=1)

def get_info():
    x = tkvar1.get()
    print (x)

button1 = ttk.Button(text='Get Information', command=get_info)

button1.grid(column=0, row=2)
window.mainloop()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I tried that but I'm not being able to create the DataFrame later on, it returns pandas.errors.EmptyDataError: No columns to parse from file , I added the steps as per suggestion and in the get_info() part I tried creating a dataframe with x: df = pd.read_csv(x)
That sounds like an issue with your inbound data? read_csv can take a file or buffer pandas.pydata.org/docs/reference/api/pandas.read_csv.html

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.