我有这个python代码
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()
当我运行此代码并打印数据时。它显示来自数据库的所有行数据。但是,当我希望数据显示在下拉菜单中时,它不能。 请帮我从下拉菜单中的数据库显示所有行(在一列中)
答案 0 :(得分:0)
这是工作:
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()