首页 > 解决方案 > 添加新项目时刷新标签

问题描述

我正在尝试使用 和 制作产品管理应用tkinter程序sqlite 3

我想在标签中展示产品。它工作正常,但我也想在添加项目时删除每个标签,然后重新创建新标签。这样,添加新项目时列表会更新。

否则用户需要重新启动应用程序才能看到新项目。这是代码:

from tkinter import *
import sqlite3

# table name = items

conn = sqlite3.connect("productManagement.db")

cursor = conn.cursor()

itemsSearch = cursor.execute("SELECT rowid, * FROM items")
itemsFetch = itemsSearch.fetchall()

window = Tk()
window.geometry("800x600")
window.config(bg="#9BB7D4")

#FUNCTIONS
itemFrame = Frame(bg="#8a8a8a",width=200,height=200)
frameTitle = Label(itemFrame,text="Products:",bg="#8a8a8a",font=("Arial Black",12))
frameTitle.pack()

def createProduct():
    global itemsFetch

    name = nameEntry.get()
    price = priceEntry.get()
    quantity = quantityEntry.get()
    number = numberEntry.get()

    cursor.execute(f"INSERT INTO items VALUES ('{name}',{int(price)},{int(quantity)}, 
    {int(number)})")

    conn.commit()

    itemsSearch = cursor.execute("SELECT rowid, * FROM items")
    itemsFetch = itemsSearch.fetchall()

    #the problem is here: i create new label for every item but the old ones doesn't 
    dissapear, i want to delete all the labels of the items existing and create new ones

    showProducts()

def showProducts():
    global itemStats

    for item in itemsFetch:
        itemStats = Label(itemFrame,bg="#8a8a8a",font=("Italic",12),
        text=f"Name: {item[1]}     Price: {int(item[2])}€     Quantity: {int(item[3])}     
        Item no: {int(item[4])}")
        deleteBtn = Button(itemFrame,text="Delete")
        itemStats.pack()

showProducts()

#GUI

title = Label(text="Product Managment System",font=("Arial Black",24),bg="#9BB7D4")
nameText = Label(text="Name:",bg="#9BB7D4",font=("Italic",12))
nameEntry = Entry(font=("Italic",12))
priceText = Label(text="Price:",bg="#9BB7D4",font=("Italic",12))
priceEntry = Entry(font=("Italic",12))
quantityText = Label(text="Quantity:",bg="#9BB7D4",font=("Italic",12))
quantityEntry = Entry(font=("Italic",12))
numberText = Label(text="Product Number:",bg="#9BB7D4",font=("Italic",12))
numberEntry = Entry(font=("Italic",12))
createProductBtn = Button(text="Create item",command=createProduct)

#PACKS

title.pack(pady=20)
nameText.place(x=140,y=140)
nameEntry.place(x=190,y=140)
priceText.place(x=340,y=140)
priceEntry.place(x=387,y=140)
quantityText.place(x=125,y=200)
quantityEntry.place(x=190,y=200)
numberText.place(x=340,y=200)
numberEntry.place(x=463,y=200)
createProductBtn.place(x=190,y=260)
itemFrame.place(x=190,y=300)

conn.commit()

window.mainloop()
conn.close()

标签: pythonsqlitetkinter

解决方案


推荐阅读