【问题标题】:Tkinter Python listboxTkinter Python 列表框
【发布时间】:2017-12-11 00:08:52
【问题描述】:

我是一个新的 python 用户。我习惯在matlab上编程。 我试图用 Tkinter 包制作一个简单的 GUI,但我遇到了一些问题。我已经阅读并搜索了我想要的东西,但我无法开发它。

我要做的是创建一个列表框,当我选择一个(或多个)选项时,索引将作为可用于索引另一个数组的变量(数组或向量)返回(并存储)。

我得到的最好结果是一个列表框,其中打印了索引,但没有存储为变量(至少它没有显示在变量列表中)

我正在使用 spyder (anaconda)。

我尝试了很多代码,但我没有这个了。

抱歉这个愚蠢的问题。我想我还在想用 Matlab 的方式来写

【问题讨论】:

    标签: python user-interface tkinter listbox


    【解决方案1】:

    为了让这个应用程序简单,你最好的选择是在你想用它做某事时获取列表框选择:

    from tkinter import Tk, Listbox, MULTIPLE, END, Button
    
    def doStuff():
        selected = lb.curselection()
        if selected: # only do stuff if user made a selection
            print(selected)
            for index in selected:
                print(lb.get(index)) # how you get the value of the selection from a listbox
    
    def clear(lb):
        lb.select_clear(0, END) # unselect all
    
    root = Tk()
    
    lb = Listbox(root, selectmode=MULTIPLE) # create Listbox
    for n in range(5): lb.insert(END, n) # put nums 0-4 in listbox
    lb.pack() # put listbox on window
    
    # notice no parentheses on the function name doStuff
    doStuffBtn = Button(root, text='Do Stuff', command=doStuff)
    doStuffBtn.pack()
    
    # if you need to add parameters to a function call in the button, use lambda like this
    clearBtn = Button(root, text='Clear', command=lambda: clear(lb))
    clearBtn.pack()
    
    root.mainloop()
    

    我还添加了一个按钮来清除列表框选择,因为默认情况下您无法取消选择项目。

    【讨论】:

    • 非常感谢。你的代码解决了我的问题。现在我知道了按钮和列表框的组合是如何工作的。我习惯使用 Matlab 中的 GUIDE 工具箱构建 GUI,其中小部件的功能无需配置即可使用。
    【解决方案2】:

    首先,导入 tkinter,然后,创建列表框。然后,您可以使用curselection 来获取列表框的内容。

    import tkinter as tk
    root = tk.Tk() #creates the window
    myListbox = tk.Listbox(root, select=multiple) #allows you to select multiple things
    contentsOfMyListbox = myListbox.curselection(myListbox) #stores selected stuff in tuple
    

    请参阅文档here

    【讨论】:

    • curselection是Listbox类的方法,必须像<Listbox object>.curselection()一样调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 2012-12-30
    • 2018-01-08
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多