我知道这个问题之前已经得到了回答,但这并没有解决我的问题。
这是错误的代码:
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()
包含insert_row方法的db_demo_2文件:
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()
答案 0 :(得分:1)
您无法从&#34; args&#34;中获取姓名/电话。您必须使用您创建的StringVar对象。另请注意,对于您在event=None
中使用的函数,我们通常使用*args
而不是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')
此代码需要与tkinter代码位于同一文件中。