I'm new to Python, so please bear with me. I'm trying to populate an optionmenu with rows from an SQLite database. The problem is that when a cell contains a space, the option appears with {} around it. What is the proper way to do this?
from tkinter import *
import sqlite3
conn = sqlite3.connect('db_name.db')
c = conn.cursor()
c.execute('''SELECT client_name FROM clients
ORDER BY client_name''')
clients = c.fetchall()
master = Tk()
variable = StringVar(master)
variable.set("Select Client")
client = OptionMenu(master, variable, *tuple(clients))
The method accepts strings for options, each separated as a positional argument (see this example from effbot).
You are actually sending tuples and not strings; because fetchall()
will return a tuple for each row, and the elements in the tuple represent columns from the result set.
As you are only selecting one column in your query, your results contain a one-tuple (a tuple with only one element):
(('Client1',), ('Client2',), ('Client 3',))
#----------^ this is a single element tuple
You need to send to the method:
client_list = OptionMenu(master, client, 'Client1', 'Client2', 'Client3')
You are actually sending:
client_list = OptionMenu(master, client, ('Client1',), ('Client2',), ('Client3',))
The reason your fix works is because it collapses the tuple, so instead of a tuple of tuples, its a tuple of strings:
>>> clients = (('Client1',), ('Client2',), ('Client 3',))
>>> sum(clients, ())
('Client1', 'Client2', 'Client 3')
There is nothing wrong with your fix, and you can implement it another way as well:
clients = [i[0] for i in c.fetchall()] # Now you have gotten rid of the
# inner tuple
You can use regular expression to get the similar result.
import re
clients = [re.sub('[{}]', '',x) for x in c.fetchall()]
I don't understand why, but this works:
client_tuple = sum(clients, ())
client_list = OptionMenu(master, client, *client_tuple)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.