Python - How To Bind a Combobox With Mysql Database Values In Python Tkinter

Python - How To Bind a Combobox With Mysql Database Values In Python Tkinter


How To Bind a Combobox With Mysql Database Values In Python Tkinter


In This Python Code We Will See How To To Populate A ComboBox With MySQL DataBase Data In Python Programming Language.




Project Source Code:

import tkinter as tk
from tkinter import *
from tkinter import ttk
import mysql.connector

connection = mysql.connector.connect(host='localhost', user='root', port='3306',
password='', database='test_py')
c = connection.cursor()

root = Tk()

frame = tk.Frame(root, padx=40,pady=40, bg='grey')


c.execute("SELECT firstname FROM `users_2`")
options = c.fetchall()
selected = StringVar(frame)
selected.set(options[0])

combobox = ttk.Combobox(frame, textvariable=selected, values=options,
font=('verdana',14))

combobox.pack()
frame.pack()

root.mainloop()




Retrieving Data from the Database:
The code executes an SQL query to select the "firstname" column from the "users_2" table in the connected database. The results are stored in the "options" variable.

Creating the Combobox:
A ttk.Combobox widget is created within the frame. 
The textvariable parameter is set to a StringVar instance named "selected," which will hold the selected option from the combobox. 
The values parameter is set to the retrieved options from the database. 
The font parameter specifies the font style and size.

Displaying the Combobox:
The combobox widget is packed within the frame, causing it to be displayed in the application window.

OutPut:

How To Populate a Combobox With Mysql Database Values In Python Tkinter





Share this

Related Posts

Previous
Next Post »