Я работаю над смарт-корзиной.В этом проекте я связал RFID-ридер с Raspberry pi.Считыватель RFID читает тег и отображает значение в таблице в графическом интерфейсе, созданном tkinter.Теперь я хочу удалить запись строки из таблицы GUI с помощью кнопки.
Я пробовал несколько кодов.Однако функция удаления (remove_all (self)), которую я использую сейчас, кажется более актуальной, но показывает ошибку атрибута.Я прилагаю мой код и ошибку.Любая помощь приветствуется
from Tkinter import *
import ttk
import sqlite3
import signal
import time
import sys
from pirc522 import RFID
class Item(object):
def __init__(self, unq_id, name, qty, price):
self.unq_id = unq_id
self.product_name = name
self.price = price
self.qty = qty
class Cart(object):
def __init__(self, master=None):
self.content = dict()
self.tree= ttk.Treeview(root, column=("column1", "column2", "column3","column4"), show='headings')
self.tree.heading("#1", text="ITEM ID")
self.tree.column("#1", anchor = "center", width=135)
self.tree.heading("#2", text="ITEM NAME")
self.tree.column("#2", anchor = "center", width=135)
self.tree.heading("#3", text="QUANTITY")
self.tree.column("#3", anchor = "center", width=135)
self.tree.heading("#4", text="PRICE(Rs)")
self.tree.column("#4", anchor = "center", width=135)
self.tree.pack()
def update(self, unq_id,product_name,price):
if unq_id not in self.content:
item = Item(unq_id,product_name,1,price)
treeRow=(item.unq_id,item.product_name,item.qty,item.price)#tuple
self.tree.insert("", END, values=treeRow)
else:
#Already exists
item = self.content.get(unq_id)
for index in self.tree.get_children():
if unq_id == self.tree.item(index)['values'][0]:
x = index
item.qty=item.qty+1
treeRow=(item.unq_id,item.product_name,item.qty,item.price)
self.tree.item(x, values = treeRow)
self.content.update({item.unq_id: item})
return
def get_total(self):
return sum([v.price * v.qty for _, v in self.content.iteritems()])
def get_num_items(self):
return sum([v.qty for _, v in self.content.iteritems()])
def remove_item(self, key):
self.content.pop(key)
def get_item(self, key):
return self.content.get(key)
class Application(Frame):
def __init__(self, master=None):
self.database = "smartShoppingCart.db"
Frame.__init__(self, master)
self.v = StringVar()
self.cart = Cart(master)
self.pack()
conn = sqlite3.connect(self.database)
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS profile(id INTEGER PRIMARY KEY, Name TEXT, Qty INT, Price REAL, rfidTag INT)")
#below test case ...will be removed later
#cur.execute("INSERT INTO profile(id,Name,Qty,Price,rfidTag) VALUES (1, 'Banana', 1, 2., 230)")
#cur.execute("INSERT INTO profile(id,Name,Qty,Price,rfidTag) VALUES (2, 'Eggs', 2, 5., 131)")
#cur.execute("INSERT INTO profile(id,Name,Qty,Price,rfidTag) VALUES (3, 'Donut', 3, 1., 128)")
#above test case ...will be removed later
conn.commit()
conn.close()
Label(root, anchor=W, fg="green", justify=RIGHT, font=("Helvetica", 16), text="Total").pack(side = LEFT)
btn = Button(root, anchor=W, justify=CENTER, font=("Helvetica", 12), text="Delete", command =remove_all(self) )
btn.pack()
Label(root, anchor=W, fg="red", justify=RIGHT, font=("Helvetica", 16), textvariable=self.v).pack(side = RIGHT)
self.v.set("0.0")
def insertItemToCart(self, rfidTag):
#fetch data from database
string ="SELECT * FROM profile WHERE rfidTag = "+str(rfidTag)
conn = sqlite3.connect(self.database)
cur = conn.cursor()
cur.execute(string)
rows = cur.fetchall()
row = rows[0]
conn.close()
#update cart
unq_id=row[4]
name=row[1]
price=row[3]
self.cart.update(unq_id, name, price)
def remove_all(self):
x = self.get_children()
print('get children values: ',x,'\n')
if x!= '()':
for child in x:
self.delete(child)
def end_read(signal,frame):
global run
print("\nCtrl+C captured, ending read.")
run = False
rdr.cleanup()
sys.exit()
signal.signal(signal.SIGINT, end_read)
run = True
rdr = RFID()
root = Tk()
root.geometry("800x300")
app = Application(master=root)
app.master.title('Smart shopping cart')
print("Starting")
while run:
app.update_idletasks()
app.update()
rdr.wait_for_tag()
(error, data) = rdr.request()
if not error:
print("\nDetected: " + format(data, "02x"))
(error, uid) = rdr.anticoll()
if not error:
print("Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3]))
time.sleep(1)
print(uid[0])
app.insertItemToCart(uid[0])
app.v.set(str(app.cart.get_total()))
print "You have %i items in your cart for a total of $%.02f" % (app.cart.get_num_items(), app.cart.get_total())
root.destroy()
Это ошибка, которая появляется в оболочке
Warning (from warnings module):
File "/usr/local/lib/python2.7/dist-packages/pi_rc522-2.2.1-py2.7.egg/pirc522/rfid.py", line 78
RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
Traceback (most recent call last):
File "/home/pi/Desktop/guitest.py", line 133, in <module>
app = Application(master=root)
File "/home/pi/Desktop/guitest.py", line 89, in __init__
btn = Button(root, anchor=W, justify=CENTER, font=("Helvetica", 12), text="Delete", command =remove_all(self) )
File "/home/pi/Desktop/guitest.py", line 113, in remove_all
x = self.get_children()
AttributeError: Application instance has no attribute 'get_children'