I'm trying to list all the data i got from my database using tkinter.
I'm following this post: https://www.geeksforgeeks.org/create-table-using-tkinter/
I got this erorr:
File "/Users/nobu/WorkSpace/Python/CommandLineApps/guineapig/guineapig/gui_tkinter.py", line 18, in __init__
self.entry.insert(END, result[i][j])
File "/usr/local/Cellar/python#3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 3056, in insert
self.tk.call(self._w, 'insert', index, string)
_tkinter.TclError: wrong # args: should be ".!entry4 insert index text"
Here's my code:
from tkinter import *
import mysql.connector
import utils
class Table:
def __init__(self,root, result):
# code for creating table
total_rows = len(result)
total_columns = len(result[0])
for i in range(total_rows):
for j in range(total_columns):
self.e = Entry(root, width=20, fg='white')
self.e.grid(row=i, column=j)
self.e.insert(END, result[i][j]) # <- Here I got an error
def get_all():
connection, cursor = utils.connect_db()
with connection:
root = Tk()
cursor.execute("SELECT * FROM item ORDER BY item_id DESC")
result = cursor.fetchall()
if len(result) == 0:
label = Label(text="There are no items. Please create one.")
else:
table = Table(root, result)
root.mainloop()
I'm very new to tkinter. Please help me solve this issue.
Thank you #Bryan Oakley!
My list has None, so I did this:
if result[i][j] is not None:
self.entry.insert(END, result[i][j])
else:
self.entry.insert(END, "None")
Related
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):
...
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()
I am trying to work around autocomplete dropdown combobox which works fine with database. but when i try to fetch data after updating database in runtime I got AttributeError: 'FarmerClass' object has no attribute 'farmer_name'. I tried other available solutions but still error is not solved. as of now, typo and syntax looks fine from the reference code which i was following.
the class which throws error
class FarmerClass(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.veg = []
self.farmer = []
self.buyers = []
self.fetch_data()
self.farmer_name = ttk.Combobox(self)
self.farmer_name['values'] = self.farmer
self.farmer_name.focus()
self.farmer_name.bind('<KeyRelease>', self.check_name)
self.farmer_name.bind('<<ComboboxSelected>>', self.get_data)
self.farmer_name.place(relx=0.028, rely=0.243, width=240, height=24)
self.product = ttk.Combobox(self )
self.product['values'] = self.veg
self.product.bind('<KeyRelease>', self.check_veg)
self.product.place(relx=0.028, rely=0.380,width=240, height=24)
self.buyer = ttk.Combobox(self )
self.buyer['values'] = self.buyers
self.buyer.bind('<KeyRelease>', self.check_buyer)
self.buyer.place(relx=0.028, rely=0.5237,width=240, height=24)
#======================= Entry btn ====================
self.entry_btn = tk.Button(self,Btn_base, text='Entry', command=self.entry_to_bill)
self.entry_btn.place(relx=0.481, rely=0.525,width=134, height=24)
def fetch_data(self, event=None):
cur.execute('SELECT * FROM vegetable ')
for i in cur.fetchall():
self.veg.append(i[0])
cur.execute('SELECT rowid, * FROM farmers ')
for i in cur.fetchall():
self.farmer.append(i[2])
cur.execute('SELECT rowid,name FROM buyers_avail ')
for i in cur.fetchall():
self.buyers.append(i[1])
self.farmer_name.configure(values= self.farmer) # getting error here
self.product.configure(values= self.veg)
self.buyer.configure(values= self.buyers)
def entry_to_bill(self, event=None):
name = self.buyer.get().lower()
cur.execute('SELECT name FROM buyers_avail WHERE name = ? ', [name])
bnames = cur.fetchall()
if bnames:
print(f'buyer {bnames} found')
else:
cur.execute('INSERT INTO buyers_avail (name) VALUES (?)',[name,])
db.commit()
self.buyer.delete(0, tk.END)
self.buyer.focus()
self.fetch_data()
if i try without those lines, farmer_name looks fine, product gets values of buyers and buyer dropdown goes empty.
please ask if anything required related to question.
The fetch_data function accesses farmer_name but you call it before defining farmer_name, which therefore doesn't exist at that point. You need to call fetch_data after defining farmer_name.
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
This isn't my code; I got it from https://www.youtube.com/channel/UC4KX0hatvRrOVy_D0nPlusg. The author didn't have the source code so I just had to type it up from the video. His worked fine but I kept getting this error:
File "D:\ProgramDevelopment\Python\Project\Python_GUI_IDEL\PythonDatabaseYoutube.py", line 45, in run_query
query_result= cursor.execute(query,parameters)
sqlite3.OperationalError: near ",": syntax error"
Link in github: https://github.com/ahmed-aya/Python_database/blob/master/Python_Database
from tkinter import *
from tkinter import ttk
import sqlite3
class Product(object):
def __init__(self,wind):
self.wind=wind
self.wind.title('IT products')
frame = LabelFrame (self.wind,text= 'Add new record')
frame.grid (row=0,column=1)
Label(frame,text='Name:').grid(row=1,column=1)
self.name =Entry(frame)
self.name.grid(row=1,column=2)
Label(frame,text='Price:').grid(row=2,column=1)
self.price =Entry(frame)
self.price.grid(row=2,column=2)
ttk.Button(frame,text='Add record',command=self.adding).grid(row=3,column=2)
self.message=Label(text='',fg='red')
self.message.grid(row=3,column=0)
self.tree=ttk.Treeview(height=10,column=2)
self.tree.grid(row=4,column=0,columnspan=2)
self.tree.heading('#0',text='Name',anchor=W)
self.tree.heading(2,text='Price',anchor=W)
ttk.Button(text='Delete record',command=self.deleting).grid(row=5,column=0)
ttk.Button(text='Edit record',command=self.editing).grid(row=5,column=1)
self.viewing_records()
def run_query (self, query, parameters=()):
with sqlite3.connect('database.db') as conn:
cursor = conn.cursor()
query_result= cursor.execute(query,parameters)
conn.commit()
return query_result
def viewing_records(self):
records = self.tree.get_children()
for element in records:
self.tree.delete(element)
query ='SELECT * FROM product ORDER BY name DESC'
db_rows = self.run_query (query)
for row in db_rows:
self.tree.insert('',0,text=row[1], values = row[2])
def validation (self):
return len (self.name.get()) !=0 and len (self.price.get()) !=0
def adding (self):
if self.validation():
query ='INSERT INTO product VALUES (NULL,?,?)'
parameters =(self.name.get(),self.price.get())
self.run_query(query,parameters)
self.message ['text'] = 'Record {} added'.format (self.name.get())
self.name.delete(0,END)
self.price.delete(0,END)
else:
self.message['text']='name field or price is empty'
self.viewing_records()
def deleting (self):
self.message['text']=''
try:
self.tree.item (self.tree.selection())['text']
except IndexError as e:
self.message['text']='Please, select recoard'
return
self.message['text']=''
name=self.tree.item (self.tree.selection())['text']
query='DELETE FROM product WHERE name=?'
self.run_query(query,(name,))
self.message['text']='Record {} deleted.'.format(name)
self.viewing_records()
def editing(self):
self.message['text']=""
try:
self.tree.item (self.tree.selection())['values'][0]
except IndexError as e:
self.message['text']='Please select record'
return
name = self.tree.item (self.tree.selection())['text']
old_price = self.tree.item (self.tree.selection())['values'][0]
self.edit_wind= Toplevel()
self.edit_wind.title('Edit Window')
Label (self.edit_wind,text='Old name: ').grid(row=0,column=1)
Entry (self.edit_wind,textvariable=StringVar(self.edit_wind,value=name),state='readonly').grid(row=0,column=2)
Label (self.edit_wind,text='New name: ').grid(row=1,column=1)
new_name = Entry(self.edit_wind)
new_name.grid(row=1,column=2)
Label (self.edit_wind,text='Old price: ').grid(row=2,column=1)
Entry (self.edit_wind,textvariable = DoubleVar(self.edit_wind,value=old_price),state='readonly').grid(row=2,column=2)
Label (self.edit_wind,text='New price: ').grid(row=3,column=1)
new_price=Entry(self.edit_wind)
new_price.grid(row=3,column=2)
Button(self.edit_wind,text='save changes', command=lambda:self.edit_records(new_name.get(),name,new_price.get(),old_price)).grid(row=4,column=2,sticky=W)
self.edit_wind.mainloop()
def edit_records(self, new_name,name,new_price,old_price):
query = 'UPDATE product SET name=?,price,=? WHERE name=? AND price =?'
parameters = (new_name,new_price,name,old_price)
self.run_query (query,parameters)
self.edit_wind.destroy()
self.message['text']='Record {} changed.'.format(name)
self.viewing_records()
if __name__== '__main__':
wind=Tk()
application = Product(wind)
wind.mainloop()
As your error says, you have a typo.
query = 'UPDATE product SET name=?,price,=? WHERE name=? AND price =?'
^ extra comma here