Home > Enterprise >  View the contents of a database joined together and separated by a hyphen in combobox
View the contents of a database joined together and separated by a hyphen in combobox

Time:11-17

How can i display the contents of the same line in a combobox (in the City1 and City2 field) combined with a dash to form a travel destination?

For example i would like to display in the combobox: London-Manchester and then Paris-Bordeaux (both destinations, so two items in the combobox).

In the code there is my attempt to solve it, but as you can see it is wrong, very wrong, you can already see it by eye. I am new to 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 window:

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

CodePudding user response:

You can combine the two fields by either

  • using SQLite concatenate operator ||
cursor.execute('SELECT city1 || "-" || city2 FROM destinations')
values = [row[0] for row in cursor]
  • or using Python string .join()
cursor.execute('SELECT city1, city2 FROM destinations')
values = ['-'.join(row) for row in cursor]

Then assign the result to values option of Combobox:

combo.config(values=values)

Full example code:

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