Search code examples
pythontkintercombobox

Python/Tkinter - combobox get value from mysql


I'm doing some tests with ComboBox and I was even successful, at first. I would like to know if I can pull the values ​​for the combobox from a mysql table.

Here is the code:

from tkinter import *
from tkinter import ttk


root = Tk()

comboBox = ttk.Combobox(root,
                        values=[
                            '',
                            'test',
                            'test2',
                            'test3',
                            'test4',
                            'test5'
                        ])

comboBox.place(x=10, y=10, width=150)
comboBox.current(0)

root.mainloop()

Solution

  • Yes, it is possible.

    pip install mysql-connector-python
    

    Then this should help:

    import mysql.connector
    
    conn = mysql.connector.connect(user='some_username', password='password',
                                   host='127.0.0.1',
                                   database='some_database')
    curs = conn.cursor()
    curs.execute('select my_column from my_table;')
    results = curs.fetchall()
    curs.close()
    conn.close()
    
    results_for_combobox = [result[0] for result in results]
    
    comboBox = ttk.Combobox(root,values=results_for_combobox])