我正在尝试从列表框中的项目列表创建列表。但是,我得到的是元组而不是实际列表。这是我正在谈论的示例,请看一下:
from tkinter import*
root=Tk()
mylistbox=Listbox(root,width=60,height=10)
mylistbox.pack()
for items in range(0,11):
mylistbox.insert(END,items)
list_of_numbers = []
list_of_numbers.append(mylistbox.get(0, END))
print(list_of_numbers)
print(list(list_of_numbers))
root.mainloop()
输出:
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)]
所需的输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
答案 0 :(得分:2)
您需要遍历mylistbox.get(0, END)
创建的元组,以将元组的每个元素添加到列表中,而不是将元组直接附加到列表中。
import tkinter as tk
root = tk.Tk()
mylistbox = tk.Listbox(root,width=60,height=10)
mylistbox.pack()
for items in range(0,11):
mylistbox.insert("end", items)
list_of_numbers = []
for item in mylistbox.get(0, "end"):
list_of_numbers.append(item)
print(list_of_numbers)
root.mainloop()
您也可以直接在list()
的结果上使用mylistbox.get(0, "end")
来获得与上述相同的结果,它成为一种方便的衬纸:
import tkinter as tk
root = tk.Tk()
mylistbox = tk.Listbox(root,width=60,height=10)
mylistbox.pack()
for items in range(0,11):
mylistbox.insert("end", items)
list_of_numbers = list(mylistbox.get(0, "end"))
print(list_of_numbers)
root.mainloop()
结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
答案 1 :(得分:1)
之所以会这样,是因为列表包含一个元组,并且该元组具有元素:
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
您需要遍历列表,然后遍历元组以提取每个元素并将它们附加到列表中。查看以下代码:
from tkinter import*
root=Tk()
mylistbox=Listbox(root,width=60,height=10)
mylistbox.pack()
for items in range(0,11):
mylistbox.insert(END,items)
list_of_numbers = []
list_of_numbers.append(mylistbox.get(0, END))
print(list_of_numbers)
mylist = []
for number in list_of_numbers[0]:
mylist.append(number)
print(mylist)
root.mainloop()
输出:
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]