问题描述
我试图在使用PySimpleGui库创建的Windows表格表中显示MongoDB数据库中的数据。以下代码已从pySimpleGUI演示程序demo_test_element.py改编而成。
传递给代码的数据将成功显示在表中,如下所示:
[[“ Dog”,“ Pack”],[“ Cattle”,“ Herd”]]
在第二个示例中,将数据检索到游标中,然后放入列表中。在显示表格时,出现 TypeError:只能将列表(而不是“ dict”)连接到列表。当我打印列表类型时,它被描述为
[{'_id':ObjectId('5f511b8a5d174ea26fbe2c64'),'name':'Dog','collective':'Pack'},{'_id':ObjectId('5f511b8a5d174ea26fbe2c65'),'name':'Cattle', 'collective':'Herd'}]
因此,我认为我将尝试更改列表,使其格式与成功版本相同。我可以实现:
[“ ['Dog','Pack']”,“ ['Cattle','Herd']”]]
如果没有双引号,那么它将遵循成功的模式。尝试在表中显示数据时,错误为 TypeError:只能将列表(而不是“ str”)连接到列表
我是Python等的新手,我可能会以错误的方式进行操作。与Tkinter相比,我更喜欢pySimpleGUI,因为我发现它更简单,但我很乐意接受使用其他GUI库的建议。我曾经使用过RDBMS(主要是Oracle),我选择MongoDB作为挑战,同样,我并不完全依赖它。
对于这个问题,我试图使代码尽可能简洁。
from pymongo import MongoClient
import PySimpleGUI as sg
# display the data in a table
def windowStuff(data):
headings = ["Animal","Collective"]
layout = [[sg.Table(values=data[0:][:],headings=headings,max_col_width=25,display_row_numbers=True,num_rows=4,alternating_row_color='red',key='-TABLE-',row_height=35)]]
window = sg.Window('The Animals',layout,)
while True:
event,values = window.read()
if event == sg.WIN_CLOSED:
break
window.close()
sg.theme('Black')
data = [["Dog","Pack"],["Cattle","Herd"]]
try:
windowStuff(data)
# This works
except Exception:
pass
# Insert and return data into Mongo Database
client = MongoClient('mongodb://localhost:27017/')
db = client.testdb
db.colCreatures.drop()
docCreatures = [ {'name': 'Dog','collective': 'Pack'},{'name': 'Cattle','collective': 'Herd'}]
db.colCreatures.insert_many(docCreatures)
curCreatures = db.colCreatures.find()
#Call the function to display the table with data,using a LIST
listCreatures = list(curCreatures)
try:
windowStuff(listCreatures)
except Exception:
# Error is File "..... \PySimpleGUI.py",line 11646,in PackFormIntoFrame
# value = [i + element.StartingRowNumber] + value
# TypeError: can only concatenate list (not "dict") to list
pass
#Call the function to display the table after the list has been manipulated
data =[]
for creature in listCreatures:
strCreature = ('[{0} {1}'.format(creature['name'] +',',creature['collective'] + ']'))
strCreature = strCreature.replace('[','[' + "'")
strCreature = strCreature.replace(']',"'" + ']')
strCreature = strCreature.replace(',"'" + ',' + "'")
data.append(strCreature)
try:
windowStuff(data)
except Exception:
# Error is File "....\PySimpleGUI.py",in PackFormIntoFrame
# value = [i + element.StartingRowNumber] + value
# TypeError: can only concatenate list (not "str") to list
pass
解决方法
您的想法是遍历这些生物并建立一个新列表。只是不要构建那个奇怪的字符串。
data = []
for creature in listCreatures:
data.append([creature["name"],creature["collective"]])