How to use a Tkinter Checkbutton to interact with a Pandas dataframe

Asked

Viewed 37 times

1

I’m trying to make an interaction with a dataframe in Pandas, I’ve tried several solution options I found here in stackoverflow, but I haven’t been successful yet. If anyone can help me, I’d be very grateful.

Goal:

For each line of the dataframe generate a Checkbutton; Choose two "cities" from the dataframe; "print" on the screen the "id" of the city; By reaching the limit of 2 cities, "printar" on the screen the limit of choice has been reached.

Problem:

I am unable to send the "id_city" to the function "on_click()"

Exit: [0] [0, 0] Limit of choice reached

Below is the code I’m banging my head on:

# -*- encoding: utf-8 -*-
from tkinter import *
import pandas as pd
import numpy as np

class Cidades:
    def __init__(self, root):
        dataframe = pd.DataFrame({"id": [1,2,3,4,5], "city":["Curitiba", "Belem", "Fortaleza", "Cuiaba", "Niteroi"]})
        self.frame = Frame(root).grid(row=0, column=0)
        
        self.total_cidades = []
        self.lista_cidades(dataframe)
   
        
    def lista_cidades(self, dataframe):
        Label(self.frame, text="ESCOLHA DUAS CIDADES").grid(row=0, column=0)
        i=0
        while i < len(dataframe["id"]):
            for row in dataframe["id"].T.iteritems():
                self.cidade = IntVar()
                id_cidade = dataframe["id"][i]
                btn_escolhe_cidade = Checkbutton(self.frame, variable=self.cidade, onvalue=id_cidade, offvalue=0, command = self.on_click)
                btn_escolhe_cidade.grid(row=i+2, column=0)
                Label(self.frame, text=dataframe["city"][i]).grid(row=i+2, column=1)
                i+=1
    
    
    
    def on_click(self):
        id_cidade = self.cidade.get()
        self.total_cidades.append(id_cidade)
        
        if len(self.total_cidades) <= 2:
            print(self.total_cidades)
        else:
            print("Limite de escolha atingido")

root = Tk()
Cidades(root)
root.mainloop()

1 answer

0

I managed to solve the problem, I used the function "partial".

from functools import partial

(...)
btn_escolhe_cidade = Checkbutton(self.frame, variable=self.cidade, onvalue=id_cidade, offvalue=0, command = partial(self.on_click, id_cidade))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.