[Python] How to change the value of cells in ipysheet without making new cells?

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm running a Jupyter notebook that, among other things, displays a simple string-to-string dictionary (with a single empty row at the bottom so the user can add new entries to the dictionary). I'm using ipysheet to do this, and I noticed that as different dictionaries were loaded into the sheet by the user multiple times without restarting the kernel, the UI thread of Jupyter Notebook would slow down and eventually crash.

    After doing some research, I found that each individual ipysheet cell was being loaded as an individual widget, and I figured that the problem was likely that I had been creating too many widgets and not discarding them after the dictionary was unloaded. I decided to try to change my code so that it only ever created exactly as many cells as were needed to display the single largest dictionary that had been loaded into memory so far in this program.

    Unfortunately, I found that I couldn't change the value of a cell once it had already been created programmatically. I tried simply setting cell_object.value = target_value, as this seemed to be the interface to all other ipysheet modifications, but found that that did not update the cells (even though I could change sheet_object.rows = new_row_number without problem.) - they continued to have the values of the original dictionary even after the new dictionary was supposed to be loaded into the sheet.

    Is there something I'm missing? Is the UI not updating properly? Are cells immutable types in ipysheet?

    def set_sheet_from_dictionary(self, target_dict):
    key_list = list(target_dict.keys())
    key_list.sort()

    key_length = len(target_dict.keys())

    with ipysheet.hold_cells():
    self.sheet1.rows = key_length+1

    for i in range(len(key_list)):
    if len(self.cell_list_a) <= i:
    # These would probably be better as Column objects? But I'm trying to keep it simple for now
    self.cell_list_a.append(ipysheet.cell(i, 0, key_list, read_only=True))
    self.cell_list_b.append(ipysheet.cell(i, 1, target_dict[key_list]))
    else:
    self.cell_list_a.value = key_list
    self.cell_list_b.value = target_dict[key_list]
    if len(self.cell_list_c) == 0:
    self.cell_list_c.append(ipysheet.cell(key_length, 0, ""))
    self.cell_list_c.append(ipysheet.cell(key_length, 1, ""))
    else:
    self.cell_list_c[0].value = ""
    self.cell_list_c[0].row = key_length
    self.cell_list_c[1].value = ""
    self.cell_list_c[1].row = key_length

    Continue reading...

Compartilhe esta Página