查看组合框中连接在一起并用连字符分隔的数据库的内容



如何在组合框中显示同一行的内容(在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()

您可以通过组合这两个字段

  • 使用SQLiteconcatenate 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]

然后将结果分配给Combobox:的values选项

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()

相关内容

最新更新