如何在組合框中(在 City1 和 City2 欄位中)顯示同一行的內容并結合破折號以形成旅行目的地?
例如,我想在組合框中顯示:倫敦-曼徹斯特,然后是巴黎-波爾多(兩個目的地,組合框中有兩個專案)。
在代碼中有我試圖解決它,但正如你所看到的那樣,這是錯誤的,非常錯誤,你已經可以親眼看到了。我是 Python 新手
CREATE TABLE "destinations" (
"id" INTEGER,
"city1" INTEGER, #London, #Paris
"city2" INTEGER, #Manchester, #Bordeaux
PRIMARY KEY("id" AUTOINCREMENT)
);
1, London, Manchester
2, Paris, Bordeaux
Tkinter 視窗:
from tkinter import *
from tkinter import ttk
import tkinter as tk
import sqlite3
app=Tk()
app.title(" ")
app.geometry("300x200")
con = sqlite3.connect('database.db')
cursor = con.cursor()
combo=ttk.Combobox(app, width=21)
combo.place(x=30, y=20)
combo.config(values=combo)
combo.bind('<<ComboboxSelected>>')
combo.set("Select")
combos=["destinations"]
city1= cursor.execute "SELECT city1 FROM destinations"
city2= cursor.execute "SELECT city1 FROM destinations"
destinations = "city1" "-" "city2"
app.mainloop()
uj5u.com熱心網友回復:
您可以通過以下任一方式組合這兩個欄位
- 使用 SQLite
concatenate operator ||
cursor.execute('SELECT city1 || "-" || city2 FROM destinations')
values = [row[0] for row in cursor]
- 或使用 Python 字串
.join()
cursor.execute('SELECT city1, city2 FROM destinations')
values = ['-'.join(row) for row in cursor]
然后將結果分配給以下values選項Combobox:
combo.config(values=values)
完整示例代碼:
import tkinter as tk
from tkinter import ttk
import sqlite3
app = tk.Tk()
app.geometry('300x200')
cnx = sqlite3.connect('database.db')
cursor = cnx.cursor()
cursor.execute('SELECT city1 || "-" || city2 FROM destinations')
values = [row[0] for row in cursor]
'''
cursor.execute('SELECT city1, city2 FROM destinations')
values = ['-'.join(row) for row in cursor]
'''
print(values)
combo = ttk.Combobox(app, width=21, values=values, state='readonly')
combo.place(x=30, y=20)
app.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358528.html
標籤:Python sql 蟒蛇-3.x sqlite 特金特
