我这里有几行代码来检测tkinter treeview
中是否已存在某个项目,然后才能在tree2
中插入所选项目。如果该项目已存在,则应打印"item exist"
如果不是,则应插入该项目。
from tkinter import ttk
import tkinter as tk
blow = [("january", "2013"),("february", "2014"),("march", "2015"),("april", "2016"),("may", "2017")]
def append_select():
cur_id = tree.focus()
for child in tree2.selection():
#for child in tree2.get_children():
if cur_id in child:
print("item exist")
elif cur_id:
tree2.insert("", tk.END, values=tree.item(cur_id)['values'])
root = tk.Tk()
root.geometry("500x500")
tree = ttk.Treeview(columns=("columns1", "columns"), show="headings", selectmode="browse")
tree.heading("#1", text="Month")
tree.heading("#2", text="Year")
for n in blow:
tree.insert("", tk.END, values=(n))
tree.pack()
b1 = tk.Button(text="append", command=append_select)
b1.pack()
tree2 = ttk.Treeview(columns=("Month", "Year"), show="headings")
tree2.heading("#1", text="month")
tree2.heading("#2", text="year")
tree2.pack()
root.mainloop()
答案 0 :(得分:0)
我在树视图中搜索了项目文本以检查重复。
def search(treeview, comparevalue):
children = treeview.get_children('')
for child in children:
values = treeview.item(child, 'values')
if comparevalue[0]==values[0] and str(comparevalue[1])==str(values[1]):
return True
return False
def append_select():
cur_id = tree.focus()
selvalue = tree.item(cur_id)['values']
print('append_select:', cur_id, selvalue)
if search(tree2, selvalue)==True:
print("item exist")
elif cur_id:
tree2.insert("", tk.END, values=selvalue)
但更简单的方法是使用项目iid。
def append_select():
cur_id = tree.focus()
selvalue = tree.item(cur_id)['values']
if tree2.exists(cur_id)==True:
print("item exist")
elif cur_id:
tree2.insert("", tk.END, cur_id, values=selvalue)