0

I am trying to create an IDE-like program for easily inserting Tkinter Widgets with a single click. But the. At the click of a button, the program is expected to insert a code from Widgets to the text area. However, whenever a button is clicked, I got IndexError: List index out of range. Please What Am I doing wrong? I have tried many other methods but none worked out. Thanks in advance.

def insert_widget_code(code):
    tex_pad.insert(tk.INSERT, code)

Widgets =[
    ["Create\nWindow", "import tkinter as tk\n\nroot = tk.Tk()\nroot.title('My Window')\nroot.geometry('600x600')\n\nroot.mainloop()"],
    ["Frame", "frm_1 = tk.Frame(root)\nfrm_1.pack()"],
    ["Label", "label_1 = tk.Label(root, text='Hello World')\nlabel_1.pack()"],
    ["Entry", "entry1 = tk.Entry(root)\nentry1.pack()"],
    ["Text", "text1 = tk.Text(root)\ntext1.pack()"],
    ["ListBox", "l_box = tk.Listbox(root)\nl_box.pack()"],
    ["Button", "btn = tk.Button(root, text= 'Hello World')\nbtn.pack()"],
    ["Checkbutton", "Check_btn = tk.Checkbutton(root, text='Hello World')\ncheck_btn.pack()"],
    ["Radiobuton", "Radio_btn = tk.Radiobutton(root, text='Hello World')\nRadio_btn.pack()"],
    ["Menu", "menu1 = tk.Menu(root)\nmenu1.add_command(label = 'Menu')\nroot.config(menu=menu1)"],
    ["Scale", "scale1 = tk.Scale(root, from_=0, to=100)\nscale1.pack()"],
    ["Scrollbar", "sb =tk.Scrollbar(root)\nsb.pack()"]
]

wn = 0
for i in Widgets:

    btn1 = tk.Button(widget_frame, text=Widgets[wn][0], bg='#272727', fg='yellow', font=('Bold', 13),
                 command= lambda: insert_widget_code(Widgets[wn][1]))
    btn1.pack(pady= 5, fill=tk.X)
    wn+=1
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • Does this [question](https://stackoverflow.com/questions/28494089/how-to-understand-closure-in-a-lambda) help? – acw1668 Jul 06 '22 at 23:07
  • Aside from the linked duplicate, please try to use iteration normally. There is no reason to calculate `wn` and use it for an index, because `i` *already is the Widget you have in mind* each time through the loop. – Karl Knechtel Aug 20 '22 at 00:57

0 Answers0