Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I populate tkinter drop-down box with data retrieved from my SQLite database?

Basically I have a cinema booking system with a database which stores what films are on and at what time date etc.. I have managed to print the contents in the format I wish to use however, I am unsure how to use this data in terms of using a tkinter drop down menu which individually shows the lines shown underneath.

import sqlite3 as lite
conn = lite.connect('Logindetails.db')

with conn:

    conn.row_factory = lite.Row
    cursor = conn.cursor()

    title = raw_input("Name of tile: ")

    query = "SELECT * FROM Viewings WHERE Title=?"
    cursor.execute(query, (title,))

    rows = cursor.fetchall()

    for row in rows:
        data = "%s %s %s %s %s" % (row["Id"], row["Title"], row["Date"], row["Time"], row["Duration"])
        print data

That is my code for retrieving the data that its required. Here is its output.

Name of tile: Frozen
1 Frozen 06/15 11:35 95
3 Frozen 06/18 11:35 95
4 Frozen 06/30 11:25 95
5 Frozen 07/02 11:45 95
6 Frozen 07/05 12:30 95

I have written the foundations of my tkinter project just unsure how to manipulate this data and import it into a drop down box of which each data set can be selected singularly.

like image 969
Daniel Vaughan Avatar asked Jan 24 '26 19:01

Daniel Vaughan


1 Answers

You could define movieList array somewhere in your code and then append the strings created in for loop to the movieList array:

movieList = []
...
for row in rows:
        data = "%s %s %s %s %s" % (row["Id"], row["Title"], row["Date"], row["Time"], row["Duration"])
        movieList.append(data)
        print data

(As a side note, you could leave out row["Id"] and row["Duration"] fields, as the former is not really important to your users and the latter is redundant)

Building the drop-down menu is easy then, using OptionMenu widget; here is a minimal example with hard-coded values, the movieList of yours will be constructed dynamically in the aforementioned for loop:

from Tkinter import *

movieList = ["1 Frozen 06/15 11:35 95", "3 Frozen 06/18 11:35 95",
        "4 Frozen 06/30 11:25 95", "5 Frozen 07/02 11:45 95",
        "6 Frozen 07/05 12:30 95"]

master = Tk()

option = StringVar(master)
option.set(movieList[0]) # Set the first value to be the default option

w = apply(OptionMenu, (master, option) + tuple(movieList))
w.pack()

mainloop()

You can get the the chosen option then by calling get() method:

option.get()
like image 112
sjaustirni Avatar answered Jan 26 '26 11:01

sjaustirni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!