Create buttons for each item in a python list using Tkinter

Asked

Viewed 1,504 times

1

I developed a software that sends consumer data to a database. I made another application to receive this data and generate a graph.

My goal is to create specific button for each consumption day. But when creating the buttons in a list using the loop for, the command sends the final index and not the expected index.

For example, the first button has index 0, but clicking on it sends the last index of the list as argument to the function that receives the command.

def tela_inicio(self):

    self.menu.destroy()
    self.menu = Tk()
    self.menu.title("Monitoramento - Sabrina")
    self.menu.geometry("1060x380+0+0")

    self.voltar = Button(self.menu, text = "Voltar", bg = "#040c31", fg = "white")
    self.voltar["command"] = self.c_menu

    self.f_dias() #Essa função me retorna os dias monitorados
    botao = list()    

    for i in range(len(self.dia)):
        #ao criar o botao o texto dele fica correto
        botao.append(Button(self.menu, text = f"{self.dia[i]}"))
        botao[i].grid()
        #A função grafico recebe o dia como argumento para plotar um grafico com os dados referente ao mesmo       
        botao[i]["command"] = lambda: self.grafico(self.dia[i])

    self.voltar.grid()
    self.menu.mainloop()

1 answer

0


I was able to solve by creating a function to display the buttons inside the loop while. The parameters i and valor are used to retrieve the key and value of the dictionary dia.

from tkinter import *

dia = {1:'domingo',2:'segunda',3:'terça',4:'quarta',5:'quinta',6:'sexta',7:'sabado'}

i = len(dia)

menu = Tk()
menu.title("Exemplo - Função Exibir Botão")
menu.geometry("500x250+150+150")


def exbir_dia(valor):    
    print(valor)


def exbir_botao(i, valor):    
    botao = Button(menu, text=dia.get(i), command = lambda: exbir_dia(valor))    
    botao.grid()


while i > 0:

    valor = dia.get(i)

    exbir_botao(i, valor)

    i -= 1 

menu.mainloop()

Exit: inserir a descrição da imagem aqui

  • Éder, unfortunately I had a problem with my laptop. But as soon as I get the chance, I’ll test it, but looking at it, I think you’ll still have the same problem. You can test for us by making a function that returns the text of the button clicked please?

  • Now, Jonas, when you press the button, you print the key and the value of the dictionary the day you name the button. Simply adapt the display button function in your project.

  • Thank you so much, Eder! Got me out of a giant lock. I was locking everything because of this kkk. Thank you very much

  • I’m glad you helped Jonas, hug and see you next time!

Browser other questions tagged

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