tkinterlistboxitemverify

Is there a way to find specific letters in a listbox in Tkinter?


This is my first question on StackOverflow. It might not be up to the standards but just a basic query. Can I check for specific letters in a Listbox in Tkinter as the title states?

My code:

task_index = tasks_list.curselection()
selected_task = tasks_list.get(task_index) + "(Done)"

    for task in tasks_list.curselection():
        tasks_list.delete(task)
        tasks_list.insert(task_index, selected_task)

I want to check if (Done) is already present in the list item and if it is, print something like "error". Hope someone can help!


Solution

  • You can go through the selected tasks, check whether the task ends with '(Done)'. If not, mark the task done by adding '(Done)' to the task:

    # assume mark_done() is executed when a button is clicked
    # to mark selected tasks done
    def mark_done():
        DONE_MARKER = '(Done)'
        for idx in tasks_list.curselection():
            task = tasks_list.get(idx)
            if not task.endswith(DONE_MARKER):
                # mark the task done
                tasks_list.delete(idx)
                tasks_list.insert(idx, f'{task} {DONE_MARKER}')
            else:
                print(f'"{task[:-len(DONE_MARKER)-1]}" already done')