【发布时间】:2019-02-02 23:27:13
【问题描述】:
使用 python 3.7.2
我想从Listbox 中检索选定的条目。
我一直在使用curselection()、selection_set() 和get() 方法,并多次重新排列它们。我也试过设置self.libo(selectmode="single")
import tkinter as tk
class Gui(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack() # ipadx=3, ipady=3
self.createWidgets()
self.createBindings()
def widget_width(iterable):
"""returns a integer based on the longest entry contained in
'iterable'. 'iterable' should be a data structure like list, dict or
tuple."""
length_counter = 0
for entry in iterable:
if len(entry) > length_counter:
length_counter = len(entry)
return length_counter
def createWidgets(self):
# Listbox LabelFrame
self.libo_lafr = tk.LabelFrame(root)
self.libo_lafr.pack(side="top", padx=2, pady=2, ipadx=2, ipady=2)
# Listbox
self.libo_entries = ("one", "two", "three", "four", "five", "six", "seven")
self.libo = tk.Listbox(
self.libo_lafr, width=Gui.widget_width(self.libo_entries),
height=len(self.libo_entries), selectmode='browse',)
self.libo.insert("end", *self.libo_entries)
self.libo.pack()
self.libo.curselection()
print(self.libo)
self.libo_selected = self.libo.selection_set(0)
print(self.libo_selected)
self.libo_selection = (self.libo.get(0))
def createBindings(self):
self.libo.bind("<<ListboxSelect>>", print(self.libo_selection))
root = tk.Tk()
audio_output_switcher = Gui(root)
audio_output_switcher.mainloop()
我只想将 Listbox 中的选定条目作为字符串。
在self.libo.curselection() 上面的版本中打印".!labelframe.!listbox"(没有“),我已经看到解包curselection()[0] 的代码示例,我还阅读了curselection() 应该返回一个列表,但如果我尝试解包它我收到了IndexError。
self.libo.selection_set(0) 打印 "None"(不带“)
self.libo.get(0) 打印“一”(不带“),self.libo.get(6) 将打印 "Seven"。所以get() 按预期工作,让我可以访问Listbox 条目的索引0-6。
还值得注意的是,我只有在关闭 GUI 后才会收到这些打印消息,我看过一些 youtube 视频,其中 tkinter GUI 会在 GUI 仍然打开的情况下实时打印到控制台。
我怀疑我在 createWidgets() 和 createBidings() 函数中的错误,在 curselection() 行之前做了一个双段。
【问题讨论】:
标签: python python-3.x tkinter listbox unpack