Home > Software design >  tkinter list index out of range
tkinter list index out of range

Time:11-01

I get error like this in the title when I run this code. I want to make TODO list but I'm getting many errors on my way :(. I can't call array (tab) in other function and I can't change column in checkbox grid.

from tkinter import *
from tkinter import messagebox as msb
win = Tk()
win.title("Checkbutton")
win.geometry("300x600")
win.resizable("False","False")
task_name = StringVar()
tab = []
tab.append("")
tab.append("")
r = 2
c = 1
cc = IntVar

def checking():
        tab[r].grid(row=r, column=1, padx=(10, 10), pady=(5, 5))

def addcheck():
    global r
    global c
    global cc

    if r < 16:
        tab.append(Checkbutton(variable = cc, text = task_name.get(), command = checking))
        tab[r].grid(row=r, column=0, padx=(10, 10), pady=(5, 5))
        r = r   1
        task_entry.delete(0, 20)
    else:
        msb.showwarning(title="DANGER", message="TOO MUCH TASKS, TAKE A REST")

text1 = Label(win, text = "TO DO:").grid(row = 1, column = 0, padx = (10, 10), pady = (30, 10))
text2 = Label(win, text = "DONE: ").grid(row = 1, column = 1, padx = (10, 10), pady = (30, 10))

task_entry = Entry(width = "20", textvariable = task_name)
task_entry.grid(row = 0, column = 0, padx = (30, 10))
add = Button(win, text = "add task", command = addcheck).grid(row = 0, column = 1, padx = (10, 10))

mainloop()

Full error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\matib\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "D:\pythonprojekty\pythonProject\main.py", line 18, in checking
    tab[r].grid(row=r, column=1, padx=(10, 10), pady=(5, 5))
IndexError: list index out of range

CodePudding user response:

You're getting the IndexError because of trying to use the global variable r in the checking() function — and the way to fix it is by explicitly passing the row value as an argument when calling it. In the code below this is being done by using a screenshot

  • Related