我正在尝试创建一个tkinter列表框并将用户选择的选项打印为列表。 到目前为止,我有:
from tkinter import *
from tkinter import ttk
main = Tk()
main.title('Test GUI')
main.geometry('700x500')
nb = ttk.Notebook(main)
nb.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')
page1 = ttk.Frame(nb)
nb.add(page1, text='Search Terms')
p1_IncludeLanguage = Listbox(page1)
p1_IncludeLanguage.configure(selectmode=MULTIPLE, width=9, height=5)
p1_IncludeLanguage.grid(row=0, column=0)
for lang in ["English", "German", "French", "Italian", "Portuguese"]:
p1_IncludeLanguage.insert(END, lang)
main.mainloop()
我想打印出列表框中的所选选项,我尝试通过p1_IncludeLanguage.curselection()
获取行号来开始,但这会导致错误TclError: invalid command name ".!notebook.!frame.!listbox"
还有其他方法可以实现吗?为什么.curselection()
无效?
答案 0 :(得分:1)
这对你有什么用?我添加了一个按钮,可以获取所选项目的列表。
from tkinter import *
from tkinter import ttk
def get_selection():
items = [languages[int(item)] for item in p1_IncludeLanguage.curselection()]
print(items)
main = Tk()
main.title('Test GUI')
main.geometry('700x500')
nb = ttk.Notebook(main)
nb.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')
page1 = ttk.Frame(nb)
nb.add(page1, text='Search Terms')
p1_IncludeLanguage = Listbox(page1)
p1_IncludeLanguage.configure(selectmode=MULTIPLE, width=9, height=5)
p1_IncludeLanguage.grid(row=0, column=0)
btnGet = Button(page1,text="Get Selection",command=get_selection)
btnGet.grid()
languages = ["English", "German", "French", "Italian", "Portuguese"]
for lang in languages:
p1_IncludeLanguage.insert(END, lang)
main.mainloop()