0
我知道這個問題已經回答過,但是這並沒有解決我的問題。Python TypeError:'Event'對象不支持索引
這是錯誤代碼:
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')
這是回溯:
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
編輯:以下是Tkinter的代碼:
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()
而且db_demo_2文件,該文件包含insert_row方法:
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()
我認爲錯誤信息解釋了發生了什麼事。你正試圖訪問一個'Event'對象,就像它是一個'List'。它不會工作。放一個'print(args)'作爲函數的第一個語句來查看你的'insert_row'函數實際上正在接收什麼。 – Himal
@Himal這是當我打印列表()時得到的結果, –
正如你所看到的,它是一個'tkinter.Event'對象。你沒有通過姓名/電話。你能否更新你的問題以包含相關的tkinter代碼?還包括'tkinter'標籤。 – Himal