[英]Tkinter Python listbox
我是新的python用户。 我习惯在matlab上编程。 我试图用Tkinter包制作一个简单的GUI,但是我遇到了一些问题。 我已经阅读并搜索了我想要的东西,但无法开发。
我想做的是制作一个列表框,当我选择一个(或多个)选项时,索引将作为变量(数组或向量)返回(并存储),该变量可用于索引另一个数组。
我得到的最好结果是一个列表框,其中打印了索引,但没有将其存储为变量(至少它没有在变量列表中显示)
我正在使用spyder(anaconda)。
我尝试了很多代码,但现在没有了。
很抱歉这个愚蠢的问题。 我想我还在想用Matlab的方式写
首先,导入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
请参阅此处的文档。
为了使该应用程序简单,最好的选择是在要使用它进行操作时获取列表框选择:
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()
我还添加了一个按钮来清除列表框选择,因为默认情况下您不能取消选择项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.