Can't load data in dropdown tkinter from database mySQL python

ぃ、小莉子 提交于 2020-05-30 08:48:14

问题


I have this python code

import MySQLdb
from tkinter import *

# Open database connection
db = MySQLdb.connect("localhost", "root", "", "wisata")

# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = "SELECT nama_wisata FROM lokasiwisata"

try:
    # Execute the SQL command
    cursor.execute(sql)
    # Fetch all the rows in a list of lists.
    results = cursor.fetchall()
    for row in results:
        print(row[0])
except:
    print("Error: unable to fecth data")

# Options list for the dropdown
list_opt = row[0] # Create the main window
root = Tk()
# Rename the title of the window
root.title("Rekomendasi Rute Wisata")
# Set the size of the window
root.geometry("450x450")
# Set resizable FALSE
root.resizable(0, 0)
# Create a variable for the default dropdown option
selected = StringVar(root)
# Set the default drop down option
selected.set(row[0])
# Create the dropdown menu
dropdown = OptionMenu(root, selected, row[0])
# Place the dropdown menu
dropdown.place(x=45, y=10)

# Create an entry
entry = Entry(root)
entry.place(x=47, y=60)

root.mainloop()  # disconnect from server
db.close()

When i run this code and print the data. It is show all row data from database. But when i want the data is show in dropdown menu, it can't. Please help me for showing all row (in one column) from database in dropdown menu


回答1:


this is work:

import MySQLdb
import Tkinter as tk
from Tkinter import *

db = MySQLdb.connect("localhost", "root", "", "wisata")
cursor = db.cursor()

sql = "SELECT nama_wisata FROM lokasiwisata"

movieList = []
try:
    cursor.execute(sql)
    results = cursor.fetchall()
    for a in results:
        data =  (a[0])
        movieList.append(data)
        print (data)

except:
    print("Error: unable to fecth data")

root = Tk()
root.title("Rekomendasi Rute Wisata")

root.geometry("450x450")
root.resizable(0, 0)

selected = StringVar(root)
selected.set(movieList[0])

dropdown = apply (OptionMenu,(root, selected) + tuple(movieList))
dropdown.place(x=45, y=10)

root.mainloop()
db.close()


来源:https://stackoverflow.com/questions/45541011/cant-load-data-in-dropdown-tkinter-from-database-mysql-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!