Akascape / CTkListbox

A simple listbox for customtkinter (extenstion/add-on)
MIT License
130 stars 14 forks source link

Errors when selecting new entry after clearing and reloading the CustomTKinter listbox #50

Closed Radian327 closed 2 months ago

Radian327 commented 4 months ago

Hi,

I'm encountering tkinter errors when I use this customtkinter listbox and do the following:

I run program, select 1 or more entries. Then run a subroutine based on selected indexes. (This works fine) Once the subroutine finishes, I execute a listbox.delete("all") to clear the list. then loop and insert new entries.

So far all looks good. New entries show.

But once I click on any entry I error with bottom one: "_tkinter.TclError: invalid command name ".!ctkframe2.!canvas.!ctklistbox.!ctkbutton"

Any insight? Is there something I'm missing to flush and reload the listbox?

Thanks

Sincerely

Radian327

infiniteTesch commented 4 months ago

I use a populate listbox function that reads from a separate pool source, in my case a folder with .txts.

I can remove and add items seamlessly just by making the changes in the folder and then run this function:

 def populate_listbox(self):
    # Clear the listbox before populating
    while self.listbox.size() > 0:
        self.listbox.delete(0)

    # Path to the 'lists' folder
    lists_folder_path = os.path.join(os.path.dirname(__file__), 'lists')

    # Check if the 'lists' folder exists
    if os.path.exists(lists_folder_path):
        # List all files in the 'lists' folder
        file_list = os.listdir(lists_folder_path)

        # Filter and sort files using natural sort order
        self.sorted_files = sorted(
            [file for file in file_list if file.endswith(".txt") and file != '.tmp'],
            key=self.natural_sort_key  # Pass the function without calling it
        )

        # Insert each file into the listbox
        for file_name in self.sorted_files:
            display_name = file_name[:-4]  # Remove the '.txt' extension
            self.listbox.insert("end", display_name)

        # Return a dictionary mapping filenames to their indices
        self.file_indices = {file_name: index for index, file_name in enumerate(self.sorted_files)}
        #file_name = filename.txt(folder path excluded)
    else:
        print(f"Folder not found: {lists_folder_path}")
Radian327 commented 3 months ago

I've found the error is induced when with the call: listbox.delete("all") #clear entries

AFTER you have already selected entries and then try to add new entries.

The "fix" is to ensure to "deactivate" the selections BEFORE you use the .delete("all") Use this to clear the list box after it has been used prior.

for i in range(listbox.size()):
    listbox.deactivate(i)

listbox.selection_clear()
listbox.delete("all")  #clear entries

Thanks

Radian327

infiniteTesch commented 3 months ago

Ah nice! Ty for sharing

Akascape commented 2 months ago

Tried to fix the issue, test to new version.