查看组合框内数据库列的内容

View the contents of a database column inside the combobox

我想查看组合框中数据库列的内容。我知道这很容易,但我做不到。我刚开始 Python。我一定是弄得一团糟,出了什么问题。我该怎么办?

请告诉我答案中的代码,因为我是 Python 的新手,可能不明白,而且这样我可以分配最佳答案。谢谢

更新了我的代码

import sqlite3

con = sqlite3.connect('folder db')
cursor = con.cursor()

def combo_city():
    cursor.execute('SELECT City FROM Table1')
    result=[row[0] for row in cursor]
    return result


city=ttk.Combobox(window, width = 25)
city['value'] = combo_city()
city.place(x=13, y=80)
city.set("Select")

您首先需要连接到数据库,然后执行所需的SQL 语句。然后,您应该根据需要使用 cursor.fetchall() or cursor.fetchone() or cursor.fetchmany(size)

这是一个例子。

import sqlite3
import tkinter as tk
from tkinter import ttk
from itertools import chain


def create_db():

    with sqlite3.connect("sample.db") as conn:
        conn.cursor().executescript("""
                            CREATE TABLE IF NOT EXISTS table1(city VARCHAR(30) PRIMARY KEY);
                            INSERT OR IGNORE INTO table1 VALUES ('Tokoyo'), ('New York');
                            """)

def load_combobox():

     with sqlite3.connect("sample.db") as conn:
        cur = conn.execute("SELECT city FROM table1")
        cities = list(chain.from_iterable(cur.fetchall()))
        combo.config(values=cities)

root = tk.Tk()

combo = ttk.Combobox(root)
combo.pack()

create_db()
load_combobox()

root.mainloop()

相关链接供您探索with statement, executescript, itertools.chain.from_iterable()