我想在組合框內查看一個資料庫列的內容。我知道這很容易,但我卻做不到。我剛剛開始接觸Python。我一定是弄得一團糟,有什么地方不對。我應該怎么做呢?
請在答案中向我展示代碼,一是因為我是Python新手,可能不明白,二是因為這樣我可以指定最佳答案。謝謝
更新了我的代碼
import sqlite3
con = sqlite3.connect('檔案夾 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("選擇")
uj5u.com熱心網友回復:
你首先需要連接到資料庫,然后執行所需的SQL陳述句。然后你應該使用cursor.fetchall()或者cursor.fetchone()或者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()_code>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/309333.html
標籤:
