I can't recover Sql data from combobox. Error: 'NoneType' object is not subscriptable

I can't recover Sql data from combobox. Error: 'NoneType' object is not subscriptable

通过 select 组合框中的一个项目,我想检索具有相同名称的数据库行 select 由其中一个字段中的组合框编辑。

例如,如果在组合框中有东京、马德里、伦敦、巴黎(从数据库的“示例”列中获得)和我 select 东京,我想要具有要在数据库 table 中搜索的“示例”列中的文本“东京”。然后单独打印该行。

我在尝试检索和打印数据时遇到错误:

TypeError: 'NoneType' object is not subscriptable

在稍微调整代码并尝试修复它时,我不再收到错误,但变量打印为 None, None, None, None.

我不需要功能广告,也不需要按钮。我只想通过 selecting 组合框来打印变量。

谁能帮帮我?谢谢

import sqlite3
from tkinter import ttk
import tkinter as tk

root = tk.Tk()
root.geometry('400x400')
root.config(bg="gray")
root.state("normal")
  
conn = sqlite3.connect('....')
cursor = conn.cursor() 

def view_combobox():
    cursor.execute('SELECT example FROM material LIMIT 2 OFFSET 2')
    values = [row[0] for row in cursor]    
    return values

example=ttk.Combobox(root, width = 21)
example.place(x=10, y=10)
example.set("Select")
example['value'] = view_combobox()
            
select_example__button3 = example.get()

#################################################
#PROBLEM IS HERE
if select_example__button3:

    cursor.execute('SELECT a, b, c, d FROM material WHERE example=?', (select_example__button3,))
    value = cursor.fetchone()

    print(value[0], value[1], value[2], value[3], value[4])     

数据库

CREATE TABLE "material" (
    "id"    INTEGER,
    "a" INTEGER,
    "b" INTEGER,
    "c" INTEGER,
    "d" INTEGER,
    "example" TEXT,
    PRIMARY KEY("id")
       

注意:我已经测试过,如果我将条件插入到一个函数中,然后使用按钮调用该函数,我将不再收到错误消息并且变量会被正确打印。但这只是一个测试,我不需要功能,也不需要按钮。我只想通过 selecting 组合框来打印变量

checked 来自 cursor.fetchone()value return。如果由于任何原因 returns empty resultset 它 returns None。所以检查从 cursor.fetchone() 获得的 value 如果它不是 None 那么只打印 value 作为

cursor.execute('SELECT a, b, c, d FROM material WHERE example=?', (select_example__button3,))
value = cursor.fetchone()
if value is not None:

    print(value[0], value[1], value[2], value[3], value[4]) 

错误 TypeError: 'NoneType' object is not subscriptable 告诉您您正在尝试对值为 None.

的变量使用下标

在您的例子中,它是 var 变量。它是 None 因为您在创建组合框后大约一毫秒调用 cursor.execute。用户不会看到组合框,更不会有机会从中选择一个值。因此,该值将是您在空字符串之前的几条语句中设置的值,因此,SQL 语句将找不到任何匹配项。

I would simply like that by selecting the combobox, the variables are printed

要运行 选择组合框时的函数,您可以绑定到<<ComboboxSelected>> 事件。它可能看起来像这样:

def select_example(event):
    selected_value = example.get()
    cursor.execute('SELECT a, b, c, d FROM material WHERE example=?', (selected_value,))
    value = cursor.fetchone()
    if value:
        print(value[0], value[1], value[2], value[3], value[4])

example.bind("<<ComboboxSelected>>", select_example)