Tkinter Treeview 显示和选择行的问题
我想把一些字符串插入到树形视图中,并且希望能完整显示这些字符串。然而,当我运行代码时,字符串在树形视图中并没有完全显示出来。我还想在树形视图中选择某一行,以便能拿回这个字符串,虽然拿回来的字符串有点对,但和我最开始插入的字符串不太一样。我使用的是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()
谢谢你抽时间来指导一个新手程序员!我非常感谢你的建议!
我尝试过调整树形视图的宽度,但似乎没有什么效果。
1 个回答
1
注意,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"])
...
结果: