I'm trying to implement a delete button to sqlite3 using pysimplegui - python

#pysimplegui box where the data will be updated
[sg.Listbox('', size= (50, 10), key='-BOX-')]
#delete function communicating to the database
def deleta_bd(x):
back.dbase = sqlite3.connect('login.db')
c = back.dbase.cursor()
sql_query = """DELETE from login where id = (?)"""
id = x
c.execute(sql_query,(id,))
back.dbase.commit()
#function call
if event == 'Excluir':
if id:
x = values['-BOX-'][0]
deleta_bd(x)
id = visualiza_bd()
window.find_element('-BOX-').update(id)
#error type
c.execute(sql_query,(id,))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type

Related

My search in python using tree view is not working/displaying the search results

This is my two functions which operate my search. The problem seems to occur with my search function when I binded it to my key releases on my search entries. However when I search with my button it works with no error messages .
def SearchCustomer(self):
connection = sqlite3.connect("Guestrecord.db")
cursor = connection.cursor()
columnID = ["title","firstName","surname","dob","payment","email","address","postcode"]
columnStr =["Title","FirstName","Surname","DOB","Payment","Email","Address","Postcode"]
self.search_table = ttk.Treeview(self.search_frame,columns=columnID,show="headings")
self.search_table.bind("<Motion>","break")
for i in range(0,8):
self.search_table.heading(columnID[i],text = columnStr[i])
self.search_table.column(columnID[i],minwidth = 0, width = 108)
self.search_table.place(x=20,y=0)
for GuestRec in cursor.execute("SELECT * FROM tb1Guest1"):
self.search_table.insert("",END,values=GuestRec)
connection.commit()
connection.close()
SearchCustomer(self)
search_icon = Image.open("search icon.png")
search_icon_resize = search_icon.resize((20,20))
search_icon = search_icon_resize
search_icon_photo = ImageTk.PhotoImage(search_icon)
self.search_firstname = Entry(self.search_frame2, width=30,bg="#e2f0d9",font=("Avenir Next",18),highlightthickness = 0,relief=FLAT)
self.search_firstname.place(x = 140, y =0)
self.search_firstname_label = Label(self.search_frame2,bg = "white", text = "First Name", font=("Avenir Next",20))
self.search_firstname_label.place(x= 20,y=0)
self.search_Surname = Entry(self.search_frame2, width=30,bg="#e2f0d9",font=("Avenir Next",18),highlightthickness = 0,relief=FLAT)
self.search_Surname.place(x = 140, y =40)
self.search_Surname_label = Label(self.search_frame2,bg = "white", text = "Surname", font=("Avenir Next",20))
self.search_Surname_label.place(x= 20,y=40)
searchButton = Button(self.search_frame2, image=search_icon_photo,height = 35, width =35, command=self.Search,bg ="white")
searchButton.place(x= 500, y = 0)
## Binding entries
self.search_firstname.bind("<KeyRelease>",self.Search)
self.search_Surname.bind("<KeyRelease>",self.Search)
def Search(self):
sFirst_Name = self.search_firstname.get()
sSurname = self.search_Surname.get()
search_rec = (sFirst_Name,sSurname)
search_rec_new = tuple(item for item in search_rec if item !="")
search_fields = ["guestFirstname","guestFirstname"]
search_SQL = "SELECT * FROM tb1Guest1 WHERE guestID LIKE '%'"
for i in range(len(search_rec)):
if search_rec[i] != "":
search_SQL += " AND " + search_fields[i] + " LIKE '%' || ? || '%'"
connection = sqlite3.connect("Guestrecord.db")
cursor = connection.cursor()
# Clearing search results
for rec in self.search_table.get_children():
self.search_table.delete(rec)
#Display the records
for GuestRec in cursor.execute(search_SQL,search_rec_new):
self.search_table.insert("",END,values=GuestRec)
connection.commit()
connection.close()
Then this is the message which pops up when I try to type in my search entries:
It may have something to do with my .self but I don't know how I would over come this error
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/tkinter/__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
TypeError: Main_menu.Search() takes 1 positional argument but 2 were given
If someone could provide a solution to my problem it would be great as I have spend seemingly a lot of time trying to figure this error out.
The function for a binding event expects an argument: the Event object. However you also use the same function for a button command which does not expect that extra argument.
So you need to add an optional argument to Search():
# event argument is optional, if not provided, it will be None
def Search(self, event=None):
...

How to get the Values from the Entry box in Tkinter?

def in_Vals():
in_win = Tk()
in_win.title("Check In Details")
in_win.geometry("700x700")
in_win.resizable(0,0)
# title
title = Label(in_win,text="Check In Details",font=("Harlow Solid Italic",30,"italic"),fg="black",bg="#fbb08c")
title.pack(anchor="center",pady=5)
#creating label's
_Id_ = Label(in_win,text="Id :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Name_ = Label(in_win,text="Name :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Date_ = Label(in_win,text="Date :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Time_ = Label(in_win,text="Time :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Number_ = Label(in_win,text="Number :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Id_.pack(anchor='w',padx=10,pady=20)
_Name_.pack(anchor='w',padx=10,pady=20)
_Date_.pack(anchor='w',padx=10,pady=20)
_Time_.pack(anchor='w',padx=10,pady=20)
_Number_.pack(anchor='w',padx=10,pady=20)
# creating submit function
def submit():
print(f"{in_val_1}\n{in_val_2}\n{in_val_3}\n{in_val_4}\n{in_val_5}")
# creating entries
Id = Entry(in_win,width=25,font=("Courier",15,'bold'))
Name = Entry(in_win,width=25,font=("Courier",15,'bold'))
Date = Entry(in_win,width=25,font=("Courier",15,'bold'))
Time = Entry(in_win,width=25,font=("Courier",15,'bold'))
Number = Entry(in_win,width=25,font=("Courier",15,'bold'))
Id.place(x=100,y=87)
Name.place(x=100,y=157)
Date.place(x=100,y=227)
Time.place(x=100,y=293)
Number.place(x=100,y=360)
#getting values
in_val_1 = Id.get()
in_val_2 = Name.get()
in_val_3 = Date.get()
in_val_4 = Time.get()
in_val_5 = Number.get()
# creating submit button
submit = Button(in_win,text="Submit",font=("Wild Latin",15,"bold"),command=submit)
submit.place(x = 250,y=450)
in_win.config(bg="#fbb08c")
in_win.mainloop()
Here the function in_vals() is a coded to take data from the ID, Name, Date, Time, Number Entries and assign the values of The entries to the variables in_val_1 to in_val_5 ,to get the values from the entry box I have used the .get() Method. but when I try to Print the Variables that I assigned to the .get() method, it prints some white Space's.
The solution for the problem same as mine is
defining the values outside the the button function does not get anything.
here I have defined out side the button function
after defining it inside the button function it gives me the desired output

Refresh labels when adding a new item

I'm trying to make a products' management app with tkinter and sqlite 3.
I want to show the products in labels. It works correctly, but I also want to delete every label when I add an item, and then recreate new labels. This way, the list updates when adding a new item.
Otherwise the user needs to restart the app to see the new item. Here's the code:
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()

sqlite3.OperationalError: near "": syntax error

i keep getting this error when i try to add a column and give it a name
sqlite3.OperationalError: near "100": syntax error
here is my code (minimal)
from tkinter import *
import sqlite3
from tkinter import messagebox
conr = sqlite3.connect("CE.db")
curr = conr.cursor()
rt = Tk()
def add():
ID = e30.get()
curr.execute('alter table cust add {}'.format(ID))
lbl30 = Label(rt, text= "Your ID")
lbl30.grid (row = 0, column = 0)
e30 = Entry(rt, width = 30)
e30.grid(row = 0, column = 1)
buttt1 = Button(rt, text = 'Submit', command = add, width = 20)
buttt1.grid(row = 1, column = 0, columnspan = 2)
rt.mainloop()
can someone please tell me what i am doing wrong and how i can fix it.
The line
curr.execute('alter table cust add {}'.format(ID))
is being formatted and executed as
alter table cust add 100
This is not valid SQLite syntax
The correct syntax can be found at:
SQlite Alter Syntax

can't get my database to connect to my maths game

Basically I am trying to get my database to connect to my GUI and display a random question, however it is simply not working, any idea?      
SQL = 'SELECT * FROM tblQuestion'
cursor = Databaseconnector.SELECT(SQL)
rows = cursor.fetchall()
rows = random.choice(rows)
print rows.Question, rows.Hint, rows.A1, rows.A2, rows.A3, rows.A4, rows.CorrectAnswer
#def create_widgets(self):
#create welcome label
label1 = Tkinter.Label(self, text = (rows(1).Question))
label1.grid(row = 0, column = 1, columnspan = 2, sticky = 'W')
ERROR: TypeError: ‘pydodbc.Row’ object is not
rows is first a collection of pydodbc.Row objects, but then you alter it to be a single pydodbc.Row object by calling random.choice:
rows = cursor.fetchall() # rows is a list
rows = random.choice(rows) # now rows is a single object
Then you try to call that object using ():
label1 = Tkinter.Label(self, text = (rows(1).Question))
which fails with the error message you provided (partially):
ERROR: TypeError: ‘pydodbc.Row’ object is not callable
The best way to solve this to use a new variable for the single row:
rows = cursor.fetchall()
random_row = random.choice(rows)
...
label1 = Tkinter.Label(self, text = (random_row.Question))

Categories