Python: 将 TextBox 值插入 SQLite 数据库

Python: Inserting TextBox value into SQLite Database

我正在尝试提取 TextBox 内容并将其插入到 SQLite 数据库中。 我正在使用 guizero 模块。

我写了这个python测试脚本

from guizero import App, PushButton,TextBox, Text,Box
import sqlite3

global x 
global name

def insertVaribleIntoTable(x):
    try:
        sqliteConnection = sqlite3.connect('DB')
        cursor = sqliteConnection.cursor()
        cursor.execute('''INSERT INTO employee VALUES (?)''',(x,))
        sqliteConnection.commit()

        cursor.execute('''SELECT emp_name FROM employee''')
        print("database content : \n")
        print(cursor.fetchall())
        cursor.close()

    except sqlite3.Error as error:
        print("Failed to insert Python variable into sqlite table", error)
    finally:
        if sqliteConnection:
            sqliteConnection.close()

def when_clicked():
    print(name)
    strname = str(name)
    print(strname)
    insertVaribleIntoTable(strname)
    name.clear()

app = App(title="Registration")

message = Text(app, text="Registration")
entrybox = Box(app, width=185, height='fill')
Text(entrybox, text='Name ', align='left')
name = TextBox(entrybox, align='left', width=185)
button = PushButton(app, text="Add", command=when_clicked)

app.display()

现在,当我在 TexyBox 中插入 userAA 并单击添加按钮时,我得到了这个输出

database content :
[('User1',), ('User2',), ('User3',), ("[TextBox] object with text 'userAA'",)]

虽然预期输出是

database content :
[('User1',), ('User2',), ('User3',), ('userAA',)]

有人知道如何解决这个问题吗?

您的 name 变量似乎有问题。它是 TextBox class 的实例,通过链继承其 __str__ 方法:Component -> Widget -> TextWidget -> TextBox.

看起来是这样的:

def __str__(self):                                                                                                                                                                                          
    return self.description

里面 TextBox class:

@property
def description(self):
    """
    Returns the description for the widget.
    """
    return "[TextBox] object with text '{}'".format(self.value)

您可以在这里探索它:https://github.com/lawsie/guizero/tree/master/guizero

所以我认为你应该使用类似的东西:

def when_clicked():
    print(name)
    strname = name.value  # str(name) will call name.descirption
    print(strname)
    insertVaribleIntoTable(strname)
    name.clear()