Home > Back-end >  how to delete elements with a specific traits from a listbox in tkinter python
how to delete elements with a specific traits from a listbox in tkinter python

Time:12-31

so I am creating a to-do list type where the user enters whatever task they have for the day and then they can give themselves a time-limit and after completing the task they can check it which will turn the font color to green and when the timer ends will remove it from the list box my problem is how can I make it so that the list box will select any tasks with the font green and then delete it

count_task=0 #to check if the task is done
def check_task():
    global count_task
    todo_list.itemconfig(
        todo_list.curselection(),
        fg="green")
    count_task =1
    todo_list.selection_clear(0, END)
def uncheck_task():
    global count_task
    todo_list.itemconfig(
        todo_list.curselection(),
        fg="white")
    count_task-=1
    todo_list.selection_clear(0, END)
def timer():
    #placing all entry widgets label and buttons for a timer
    def countdowntimer():
        try:
            times=int(hrs.get())*3600   int(mins.get())*60   int(sec.get())
        except:
            print("Input the correct value")
        while times > -1:
            minute, second = (times // 60, times % 60)
            hour = 0
            if (minute > 60):
                hour, minute = (minute//60 , minute`)
            sec.set(second)
            mins.set(minute)
            hrs.set(hour)
            root1.update()
            time.sleep(1)
            if(times == 0):
                sec.set('00')
                mins.set('00')
                hrs.set('00')
                if(count_task==0):
                    mb.showwarning("Task not accomplished","Focus on your work  no task has been completed yet")
                elif(count_task>0):   #the problem I have is here
                   
            times -= 1

I have checked if there is any task that has been completed but I don't know any function which will iterate through a Listbox and check if any item has the font color of green

CodePudding user response:

You can go through each item in the list in reverse order and get the item foreground color using itemcget(). If the foreground color is green, delete the item:

...
elif(count_task>0):   #the problem I have is here
    # loop through all item in the listbox in reverse order
    for i in range(todo_list.size()-1, -1, -1):
        # if item foreground color is green, delete it
        if todo_list.itemcget(i, 'foreground') == 'green':
            todo_list.delete(i)
...

Note that as I said in the answer of your other question, using while loop in main thread of a tkinter application should be avoided.

  • Related