0

I am attempting to make a table of buttons in tkinter (specifically custom tkinter, but that should not change anything here). It does not necessarily have to be buttons, but I want an interactable table where I can determine which cell was clicked and buttons seemed the easiest way of doing so. I dynamically create these buttons with text, and want to be able to change this text as the data of the table changes.

I am currently unable to pass through the current text of a button to the function of the button. I have tried using "button.text", a stringvar array, and a string array as the arguments to the button command, but they all resulted in every button passing through the value used in the last button configuration. Is there another way I should be setting the button command?

class CTkTable(ctk.CTkFrame):

    def __init__(self, master, size = 10):
        super().__init__(master=master, corner_radius=0)
        self.activeButton = 0
        self.defaultColor = 'gray'
        self.activeColor = 'orange'
        self.button_array = [None for i in range(size)]
        self.button_text_array = [None for i in range(size)]
        self.grid_rowconfigure(tuple(range(size)), weight=1, uniform='r')

        for i in range(size):
            self.button_array[i] = ctk.CTkButton(master = self)
            self.button_text_array[i] = str(i)
            self.button_array[i].configure(fg_color=self.defaultColor)
            self.button_array[i].grid(row=i, sticky="nsew", pady=(0, 2))

        self.setCellsValue(range(size), [self.button_text_array[i] for i in range(size)])

    def setCellsValue(self, locations, values):
        for i in range(len(locations)):
            self.button_text_array[locations[i]] = values[i]
            self.button_array[locations[i]].configure(text = values[i], command = lambda: self.buttonPressed(self.button_text_array[i]))


    def buttonPressed(self, text):
        print(text)
        self.button_array[self.activeButton].configure(fg_color=self.defaultColor)
        for i in range(len(self.button_array)):
            if(self.button_array[i].text == text):
                self.activeButton = i
                self.button_array[self.activeButton].configure(fg_color=self.activeColor)
Dak
  • 19
  • 5

0 Answers0