如何从SQL填充组合框数据?使用Python

2024-05-23 18:35:51 发布

您现在位置:Python中文网/ 问答频道 /正文

(图1)-这是我的简单程序的输出,假设它有5个下拉项来自数据库,但它只显示1个数据,这是数据库的最后一行被读取。在

图1-

enter image description here

(图2)-这是我用于loop的代码,我希望它循环通过它并显示来自db的每个数据,但它只显示最后一行。是语法错误还是逻辑错误?在

# Combobox - Subjects
self.cbSubjects = ttk.Combobox(root, width=17, textvariable=self.cbSubjects)
self.cbSubjects.place(x=120, y=60)

# SQL Command
self.conn = cx_Oracle.connect('system/system@127.0.0.1/xe')
self.cursor = self.conn.cursor()
self.cursor.execute("SELECT hr.subject.description FROM hr.subject")
for i in self.cursor:

   self.cbSubjects['values'] = (i)
   self.cbSubjects.current(0)

self.cursor.close()
self.conn.close()

(图3)-下面是我想在组合框中显示的SQL数据

图3-

enter image description here

我是Python tkinter新手。非常感谢你!在


Tags: 数据代码self程序loop数据库closesql
1条回答
网友
1楼 · 发布于 2024-05-23 18:35:51

for循环中,您只需覆盖组合框中的单个值,即执行此行的原因:self.cbSubjects['values'] = (i)。分配给它的最后一个值是SELECTSQL语句返回的最后一行。这就是你面对这个问题的原因。在

对于解决方案,如果您看看documentation,它通常是您最好的朋友,您可以阅读以下内容:

values Specifies the list of values to display in the drop-down listbox.

实际上这有点误导,因为self.cbSubjects['values']是一个元组,而不是一个列表,而且正如您所知,元组是不可变的,与列表不同,但是您仍然可以通过使i穿着具有一个元素的元组的衣服来克服这个问题。在

也许有了代码,你会更好地理解这个想法:

#...
for i in self.cursor:   
   # self.cbSubjects['values'] = (i) , this is bad, change it like this:
   self.cbSubjects['values'] = self.cbSubjects['values'] + (i, )
   # ... rest of your program

相关问题 更多 >