【问题标题】:python tkinter fill optionmenu with list from functionpython tkinter使用函数列表填充选项菜单
【发布时间】:2020-12-27 20:04:02
【问题描述】:

我已经创建了一个 tkinter GUI。

我已将函数def scrape 绑定到按钮。 当我按下按钮时,selenium 会从不同的元素中获取数据并将它们存储在不同的列表中。

在我的 GUI 中,我希望每个列表都有一个 OptionMenu

问题是,列表是在我按下按钮后创建的。

当我想将OptionMenu 添加到 GUI 并加载一个列表作为值时,我得到一个错误,没有变量“列表”。这是因为app.mainloop() 启动时还没有创建列表。

这是我的抓取代码:

def scrape():
    li_leagues = []
        print('Getting leagues...\n')
        #click the dropdown menue to open the folder
        league_dropdown_menu = driver.find_element_by_xpath('/html/body/main/section/section/div[2]/div/div[2]/div/div[1]/div[1]/div[7]/div')
        league_dropdown_menu.click()
        time.sleep(1)
        
        # scrape all text
        scrape_leagues = driver.find_elements_by_xpath("//li[@class='with-icon' and contains(text(), '')]")
        for league in scrape_leagues:
            export_league = league.text
            export_league = str(export_league)
            export_league = export_league.replace(',', '')
            li_leagues.append(export_league)

这是我为OptionMenu尝试的:

str_quality = StringVar()
str_quality.set(li_quality[0])

#Dropdown
d_quality = OptionMenu(app, str_quality, *li_quality)

如何才能将OptionMenu 添加到我的 GUI 中?

编辑:

在调用app.mainloop() 之前,我将列表名称作为空列表li_quality = [] 添加到代码中。

现在正在使用 OptionMenu 加载 GUI。但是在我抓取数据后它没有更新。

【问题讨论】:

    标签: python list function tkinter optionmenu


    【解决方案1】:

    我不确定这是否是你想要的,但我在互联网上找到了一些东西并修改了一点,看看:

    from tkinter import *
    
    root = Tk()
    
    def hey():
        lst = [1,2,3,4]
        m = a.children['menu']
        for val in lst:
            m.add_command(label=val,command=lambda v=sv,l=val:v.set(l))
    
    sv = StringVar()
    dummy = []
    a = OptionMenu(root,sv,*dummy)
    a.pack()
    
    b = Button(root,text='Click me',command=hey)
    b.pack()
    
    root.mainloop()
    

    这里,a 最初设置为一个空列表,但在您单击按钮后,它将从列表中填充。

    Here is the link to the discussion

    替代方法:

    无论如何,我建议稍后在收到项目后在函数内部创建OptionMenu,或者使用其他能够执行此操作的小部件。我很确定ttk.Combobox 是可能的。

    看看下面如何使用Combobox

    from tkinter import *
    from tkinter import ttk
    
    root = Tk()
    
    def hey():
        lst = [1,2,3,4]
        a.config(value=lst)
    
    dummy = []
    a = ttk.Combobox(root,value=dummy,state='readonly')
    a.pack()
    
    b = Button(root,text='Click me',command=hey)
    b.pack()
    
    root.mainloop()
    

    希望对你有所帮助,如有错误请告诉我。

    干杯

    【讨论】:

    • 谢谢!方法 1 在我将其修改为我的代码后完成了这项工作! :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多