Listing and selecting columns of DataFrame by Checkbuttons


Tkinter Selection of Pandas DataFrame columns
select_file():Create DataFrame from the path slected by user.
my_columns(): Create checkbuttons against each column of DataFrame.
my_update() : Create List using selected columns & display.


Listing of columns of DataFrame in Tkinter window for user to select Part VI

select_file()

Use the file browser to open any csv ( Comma Separated value ) file or Excel file on click of a button b1. Use the read_csv() method or read_excel() based on file type to create a Pandas Dataframe. At the end my_columns() is called to show the CheckButtons.
def select_file():
    f_types=[('CSV files','*.csv'),('Excel files','*.xlsx')]
    file_path=filedialog.askopenfilename(filetypes=f_types)
    if file_path:
        lb1.config(text=file_path) # show the file path in Label
        global l1,i,my_ref
        if file_path.endswith('.csv'): # type of file extension 
            df=pd.read_csv(file_path) # create dataframe
        else:
            df=pd.read_excel(file_path)
        l1=list(df) # List of column names as header 
        my_columns() # call to show the checkbuttons

my_columns()

Based on the columns in DataFrme, the list ( l1 ) is prepared in above code. From this list the CheckButtons are dynamically created. Each checkbutton is connected to my_update() function on change of status.
def my_columns():
    global l1,i,my_ref
    i=1 # to increase the column number 
    my_ref={} # to store references to checkboxes 
    lb.config(text=' ') # Remove previosly displayed columns
    for w in my_w.grid_slaves(3): # all widgets of row 3
        w.grid_forget()  # remove the widgets 
    for k in l1: # Loop through all headers 
        my_ref[k]=tk.BooleanVar() # variable 
        ck = tk.Checkbutton(my_w, text=k,onvalue=True,offvalue=False,
            font=font1,command=lambda: my_update(),variable=my_ref[k])
        ck.grid(row=3,column=i,padx=2,pady=25)
        i=i+1 # increase the column value 

my_update()

By using my_ref[] we can get the list of all checked CheckButtons. This one line code will do that for us.
column_search = [v for v in my_ref if my_ref[v].get()]
There is another way also to do the same thing.
After creating the list with selected columns (column_search), the vlaues are displayed by using config() method of Label lb.
Full code is here
def my_update(): # called when checkbutton is clicked 
    global my_ref
    column_search = [v for v in my_ref if my_ref[v].get()]

    ### One more way to Create the same List of checked columns 
    #column_search=[] # create a blank list 
    for j in my_ref:
        pass # 
        #print(j,my_ref[j].get()) # Key and value 
        #if my_ref[j].get():
        #    column_search.append(j)
              
        #print(column_search) # print the selected column names 
    lb.config(text=' '.join(column_search)) # Show in the Label
import tkinter as tk # Tkinter Library
import pandas as pd  # Pandas Library 
from tkinter import filedialog # File selection 

my_w = tk.Tk() # Parent window 
my_w.geometry("650x300")  # width x height
my_w.title("plus2net.com")  # Adding a title
font1=['Times',18,'normal'] # Higher size font 

b1 = tk.Button(my_w, text='Browse File', 
   width=20,command = lambda:select_file())
b1.grid(row=1,column=1,padx=5,pady=5)
lb1=tk.Label(my_w,bg='lightgreen',text='',font=font1) # Path 
lb1.grid(row=1,column=2,padx=5,columnspan=2)
lb=tk.Label(my_w,bg='yellow',text='',font=font1) # List display
lb.grid(row=2,column=1,padx=10,pady=10,columnspan=4)

#file_path="F:\\data\\student.xlsx"
my_ref={} # to store references to checkboxes 
i=1
column_search=[] # To store the checkbuttons which are checked

def select_file():
    f_types=[('CSV files','*.csv'),('Excel files','*.xlsx')]
    file_path=filedialog.askopenfilename(filetypes=f_types)
    if file_path:
        lb1.config(text=file_path) # show the file path in Label
        global l1,i,my_ref
        if file_path.endswith('.csv'): # type of file extension 
            df=pd.read_csv(file_path) # create dataframe
        else:
            df=pd.read_excel(file_path)
        l1=list(df) # List of column names as header 
        my_columns() # call to show the checkbuttons

def my_columns():
    global l1,i,my_ref
    i=1 # to increase the column number 
    my_ref={} # to store references to checkboxes 
    lb.config(text=' ') # Remove previosly displayed columns
    for w in my_w.grid_slaves(3): # all widgets of row 3
        w.grid_forget()  # remove the widgets 
    for k in l1: # Loop through all headers 
        my_ref[k]=tk.BooleanVar() # variable 
        ck = tk.Checkbutton(my_w, text=k,onvalue=True,offvalue=False,
            font=font1,command=lambda: my_update(),variable=my_ref[k])
        ck.grid(row=3,column=i,padx=2,pady=25)
        i=i+1 # increase the column value 
        
def my_update(): # called when checkbutton is clicked 
    global my_ref
    column_search = [v for v in my_ref if my_ref[v].get()]

    ### One more way to Create the same List of checked columns 
    #column_search=[] # create a blank list 
    for j in my_ref:
        pass # 
        #print(j,my_ref[j].get()) # Key and value 
        #if my_ref[j].get():
        #    column_search.append(j)
              
        #print(column_search) # print the selected column names 
    lb.config(text=' '.join(column_search)) # Show in the Label
my_w.mainloop()
Part I : Searching DataFrame and displaying result in Treeview
Projects in Tkinter
Create Pandas DataFrame by reading Google Analytics csv file from Tkinter GUI Search DataFrame by user inputs through Tkinter. Browsing directory and displaying file details with sorting using Treeview
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer