Anupama_K
Anupama_K

Reputation: 95

Python TypeError: 'Event' object does not support indexing

I know that this question has been answered before but that does not solve my problem.

This is the faulty code :

def insert_row(*args):
        for i in args:
            name1 = i[0]
            phone1 = i[1]
            c.execute('''INSERT INTO users(name,phone)VALUES(?,?)''', (name1, phone1))
            print('Record inserted')

And this is the traceback :

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\ak00479324\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
    return self.func(*args)
  File "D:/ak00479324/TECHM/Python POC\db_demo.py", line 13, in insert_row
    name1 = i[0]
TypeError: 'Event' object does not support indexing

Edit : Following is the tkinter code :

from tkinter import *
from tkinter import ttk
import db_demo_2

root = Tk()
root.title("Form")

frame = ttk.Frame(root, padding="20 20 50 50")
frame.grid(column=0, row=0, sticky=(N, W, E, S))

name = StringVar()
phone = StringVar()

name_entry = ttk.Entry(frame, width=20, textvariable=name)
name_entry.grid(column=3, row=1, sticky=(W, E))

phone_entry = ttk.Entry(frame, width=20, textvariable=phone)
phone_entry.grid(column=3, row=2, sticky=(W, E))

ttk.Button(frame, text="Enter", command=db_demo_2.insert_row).grid(column=3, row=3, sticky=W)

ttk.Label(frame, text="Name").grid(column=1, row=1, sticky=W)
ttk.Label(frame, text="Phone").grid(column=1, row=2, sticky=W)

for child in frame.winfo_children(): child.grid_configure(padx=10, pady=10)

name_entry.focus()
root.bind('<Return>', db_demo_2.insert_row)

root.mainloop()

And the db_demo_2 file which contains the insert_row method :

import sqlite3

sqlite_file = 'db_1.sqlite'

conn = sqlite3.connect(sqlite_file)
c = conn.cursor()

c.execute('''CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name TEXT, phone INTEGER)''')

def insert_row(*args):
    print(*args)
    name1 = args[0]
    phone1 = args[1]
    for i in args:
        c.execute('''INSERT INTO users(name,phone) VALUES(?,?)''',(name1,phone1))
        print('Record inserted')

conn.commit()

Upvotes: 0

Views: 797

Answers (1)

Novel
Novel

Reputation: 13729

You can't get the name / phone out of the "args". You have to use the StringVar objects you created. Also note that we generally use event=None instead of *args for a function that you use in bind.

def insert_row(event=None):
    name1 = name.get() # get the value from the "name" StringVar
    phone1 = phone.get()
    c.execute('''INSERT INTO users(name,phone)VALUES(?,?)''', (name1, phone1))
    print('Record inserted')

This code needs to be in the same file as the tkinter code.

Upvotes: 1

Related Questions