遍历树视图时如何编写 if 子句?

How to write the if clause when iterating through a treeview?

我有一个功能可以检查仓库是否知道条形码。如果是这样,该函数从数据框中抓取行(由导入的 excel 文件占用)并将插入到包含已知项的树视图中。如果条形码未知,它将被插入到列表框中。

该函数有效并完成了它应该做的事情,但我想通过在将相同的条形码添加到树视图时将其数量增加 1 来更新树视图中的行来扩展它。查看当前行为的图片。 Known items treeview

# Function to process new entered barcodes by filtering known and unknown items and adding them to treeview
def scan_check(event):
    scanned_item = scan_entry.get()
    for code in df.iloc[:, 1]:  # column with barcodes
        if code == scanned_item:
            for row in df.to_numpy().tolist():  # dataframe with item / barcode / item description / size / quantity
                if scanned_item in row:
                    quantity_count = 1
                    row.insert(4, quantity_count)
                    scanTree.insert(parent='', index='end', value=row)
                    for child in scanTree.get_children():
                        if scanTree.item(child, option='values'[3]) in scanTree.get_children():
                            quantity_count += 1
                            scanTree.set(child, 'Quantity', quantity_count)
                  
            scan_entry.delete(0, tkinter.END)

            break   # to prevent adding item to unknown products listbox as well

    else:
        unknown_listbox.insert(tkinter.END, scanned_item)
        scan_entry.delete(0, tkinter.END)

我的问题是:在遍历子项之后,当我想检查从数据框中添加的行是否已经在我的树视图中时,我该如何编写 if 子句?

我对 if 子句的尝试显然没有奏效。我希望有人能帮助我解决我的问题。感谢阅读。

你可以简化逻辑:

  • 首先在树视图中搜索条形码,如果找到,更新数量
  • 如果找不到,请搜索数据框。如果找到,将新记录插入树视图,否则将条形码插入未知列表框
def scan_check(event):
    scanned_item = scan_entry.get().strip()
    if scanned_item == '':
        # do nothing if empty string is input
        return

    # search treeview
    for child in scanTree.get_children():
        row = scanTree.set(child)
        if row['Barcode'] == scanned_item:
            # update quantity
            scanTree.set(child, 'Quantity', int(row['Quantity'])+1)
            break # prevent executing else block
    else:
        # search dataframe
        result = df.loc[df['Barcode'].astype(str) == scanned_item]
        if result.empty:
            # should check whether barcode already exists?
            unknown_listbox.insert('end', scanned_item)
        else:
            scanTree.insert('', 'end', values=result.iloc[0].to_list()+[1])
    scan_entry.delete(0, 'end')