问题描述
我想用以前从网址中抓取的数据填充一些OptionMenu
。
例如:
with open('clubs.csv',newline ='') as club:
reader=csv.reader(club)
dummy_club = []
dummy_club.extend(reader)
稍后我想在我的OptionMenu
之一中使用它
例如:
sv_club = StringVar()
d_club = OptionMenu(app,variable=sv_club,value=dummy_club)
不幸的是,大约700个项目的列表全部放在一行/行中,就像在此屏幕快照上单击d_club OptionMenu
时一样:
当我将抓取的数据作为列表直接导入到OptionMenu
中时,它看起来很完美。
但是,当我在启动GUI时尝试导入.csv中保存的数据时(因此,当我调用app.mainloop()
时)就搞砸了。
编辑:
def scrape():
li_clubs = []
print('getting clubs...\n')
#click the dropdown menue to open the folder
club_dropdown_menu = driver.find_element_by_xpath('/html/body/main/section/section/div[2]/div/div[2]/div/div[1]/div[1]/div[8]/div')
club_dropdown_menu.click()
time.sleep(1)
# scrap all text
scrape_clubs = driver.find_elements_by_xpath("//li[@class='with-icon' and contains(text(),'')]")
for club in scrape_clubs:
export_clubs = club.text
export_clubs = str(export_clubs)
export_clubs = export_clubs.replace(',','')
li_clubs.append(export_clubs)
m_club = d_club.children['menu']
for val in li_clubs:
m_club.add_command(label=val,command=lambda v=sv_club,l=val:v.set(l))
with open('clubs.csv','w',newline='') as club:
writer = csv.writer(club,quotechar=None)
for i in li_clubs:
writer.writerow(i.split(','))
代码是这样构建的,因此我可以根据需要更新OptionMenu。
函数def scrape():
绑定到按钮。这样,当我按下utton时,我会刮一下并更新我的optionMenu。
之后,我将列表li_clubs
写入一个clubs.csv
文件中。
由于我所需的数据不会经常更改,因此我将废品绑定到了一个按钮,以便可以按需推送。
但是我想在每次启动后将.csv文件中的数据加载到我的OptionMenu中。这样我就可以直接使用抓取的数据。
解决方法
您需要使用扩展/解压/ splat运算符*
。但是,由于数据是列表列表(或元组的元组),因此您需要先将内部列表转换为字符串,因为选项菜单需要一个字符串列表。
它可能看起来像这样:
dummy_club = [" ".join(row) for row in dummy_club]
d_club = OptionMenu(app,sv_club,*dummy_club)
尽管如此,具有700个值的OptionMenu很难使用。您可能应该考虑使用ttk组合框小部件。