我想将以下字符串插入到树视图中并显示完整的字符串,但是当我运行代码时,该字符串没有完全显示在树视图中。我还想选择树视图中的行来取回字符串,该字符串在某种程度上是正确的,但与最初插入的字符串不同。我正在使用Python 3.6。下面是我正在使用的代码和我观察到的一些示例输出。请就两件事向我提出建议:
import tkinter as tk
import tkinter.ttk
selected_from_list = []
def select():
curItems = tree.selection()
for x in curItems:
print(x)
selected_from_list.append(tree.item(x)['values'])
print(selected_from_list)
print(selected_from_list)
print([str(tree.item(i)['values']) for i in curItems])
tk.Label(root, text="\n".join([str(tree.item(i)['values']) for i in curItems])).pack()
root = tk.Tk()
tree = tkinter.ttk.Treeview(root, height=4)
tree['show'] = 'headings'
tree['columns'] = ('File path')
tree.heading("#1", text='Badge Name', anchor='w')
tree.column("#1", stretch="no")
tree.pack()
tree.insert("", "end", values="C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 1.xlsx")
tree.insert("", "end", values="C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 2.xlsx")
tree.insert("", "end", values="C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 3.xlsx")
tree.bind("<Return>", lambda e: select())
root.mainloop()
感谢您抽出时间来指导新手编码器!我非常感谢您的意见!
我尝试调整树视图宽度,但似乎没有什么区别
请注意,
columns
和 values
选项都需要一个元组/列表,但您向它们传递了一个字符串。看起来字符串将被底层 TCL 解释器隐式地用空格分割,您将得到发布图像中显示的内容。
将正确的类型传递给以下两个选项:
...
tree['columns'] = ('File path',) # changed to tuple by adding a comma before the ending )
...
tree.column("#1", stretch="no", width=400) # set larger width to show the content
...
# pass list to values option
tree.insert("", "end", values=["C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 1.xlsx"])
tree.insert("", "end", values=["C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 2.xlsx"])
tree.insert("", "end", values=["C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 3.xlsx"])
...
结果: