Akascape/CTkListbox

Issue with moving options up and down

derrickcodez opened this issue · 5 comments

Hi,

When moving options in a listbox up and down it seems to glitch out (I think its related to something in the insert method). The code below works in tkinter but not Ctk.

import customtkinter
from CTkListbox import *

def show_value(selected_option):
    print(selected_option)
    
root = customtkinter.CTk()


def moveup():
    try:
        idxs = tuple([animalBox.curselection()])
        if not idxs:
            return
        for pos in idxs:
            if pos==0:
                continue
            text=animalBox.get(pos)
            animalBox.delete(pos)
            animalBox.insert(pos-1, text)
            animalList.pop(pos)
            animalList.insert(pos-1, text)
        animalBox.select(pos-1)
    except:
        pass

animalList = ['Cat', 'Dog', 'Bear', 'Dolphin', 'Kangaroo']
animalString = customtkinter.StringVar(value=animalList)

animalBox = CTkListbox(root, command=show_value,listvariable=animalString)
animalBox.grid(row=1, column=0,padx=20, pady=10)



moveupButton = customtkinter.CTkButton(root,text="Move Up",command=moveup,width=200,height=35)
moveupButton.grid(row=2, column=0,padx=20, pady=10)

root.mainloop()

Hi,

I have just managed how to do what this issue is looking for...

I know this is not encapsulated at first instance, for it will work for now.

Dev Solution


    def display_clientes(self):
        listbox = CTkListbox(self, command=lambda x: print(x), text_color="#000", listvariable=listvariable)
        listbox.bind("<Down>", lambda event: self.entry_on_keyup_keydown(listbox, 1))
        listbox.bind("<Up>", lambda event: self.entry_on_keyup_keydown(listbox, -1))
        listbox.grid(row=1, column=0)

    def on_keyup_keydown(self, widget, direction):
        current_index = widget.curselection()
        next_index = (current_index + direction) % widget.size()
        widget.activate(next_index)

Hope that helps.

Edit:

Note: this only will work with no multiselection

@SilasPDJ

Thanks for your help—I'll definitely incorporate this as a feature. However, my main concern revolves around the functionality of swapping options in the listbox. Specifically, I want the ability to select an option, click the 'Move Up' button, and have the selected option move upward in the list.

Hi @derrickcodez ,

I've created a pull request #18 that introduces two new methods to address the reported issue. The new methods, move_up and move_down, provide a more optimized solution. Please review and let me know your thoughts or if any further adjustments are needed.

Thanks!

Please @derrickcodez, take a look at this issue about the scrollbar right here:
#18 (comment)

@CheemaOTB, your solution worked perfectly, huge thanks! And kudos to @SilasPDJ for the arrow keys feature, super useful!