Good,
I'm trying to sum the values of a column, while inputting it. Since I put a code in the entry and check if it exists and put it in columns in treeview, and I would like to add only the "price" values, but I can't do it, I get the data from the price column, but I can't get if This 5.99 I have entered another 5.99 add up and give me a total, as I add a price.
What I can be doing wrong? or what I have wrong
Any additional information would be appreciated.
def Cesta(self):
self.conex()
self.b_codigo = self.s_Codigo.get()
self.sql3 = "SELECT * FROM productos WHERE codigo = %s"
self.mycursor.execute(self.sql3,[(self.b_codigo)])
self.r_codigo = self.mycursor.fetchall()
self.row3 = [item['nombre'] for item in self.r_codigo]
if self.s_Codigo.get() == "":
MessageBox.showinfo("ERROR", "DEBES INTRODUCIR DATOS", icon="error")
elif self.r_codigo:
for self.x2 in self.r_codigo:
print (self.x2["nombre"], self.x2["talla"], self.x2["precio"]+"€")
self.tree.insert('', 'end', text=self.x2["nombre"], values=(self.x2["talla"],self.x2["precio"]+" €"))
print(self.x2["fecha"])
for self.item in self.tree.get_children():
self.resultado = 0
self.celda = int(self.tree.set(self.item,"col2"))
self.total = int(self.resultado) + int(float(self.celda))
print(self.total)
else:
MessageBox.showinfo("ERROR", "EL CODIGO INTRODUCIDO NO ES CORRECTO", icon="error")
self.clear_entry()
`
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/tkinter/__init__.py", line 1921, in __call__
return self.func(*args)
File "/Users/tomas/Downloads/PROYECTO/main.py", line 205, in Cesta
self.celda = int(self.tree.set(self.item,"col2"))
ValueError: invalid literal for int() with base 10: '134,99 €'
[Finished in 6.7s]
`
self.tree = ttk.Treeview(self.pagina1,columns=("col1","col2"), height=50)
self.tree.grid(column=0, row=2, padx=50, pady=100)
### COLUMNAS ###
self.tree.column("#0",width=250)
self.tree.column("col1",width=150, anchor=CENTER)
self.tree.column("col2",width=150, anchor=CENTER)
### NOMBRES COLUMNAS ###
self.tree.heading("#0", text="Articulo", anchor=CENTER)
self.tree.heading("col1", text="Talla", anchor=CENTER)
self.tree.heading("col2", text="Precio", anchor=CENTER)
Everything else is going well for me, but the part in which I want to add the results of the price column does not
What am I doing wrong, to be able to add the values of the prices column every time I insert a new product?
I have already managed to solve the error, the new price is already added to the old one, thanks for making me reflect on it.
for self.x2 in self.r_codigo:
print (self.x2["nombre"], self.x2["talla"], self.x2["precio"]+"€")
self.tree.insert('', 'end', text=self.x2["nombre"], values=(self.x2["talla"],self.x2["precio"]))
self.total = 0
for self.item in self.tree.get_children():
self.celda = float(self.tree.set(self.item,"col2"))
self.total+=self.celda
print(self.total)
Related
I have the following problem with this part of my code I explain
What this function does is get the data from the DB and then fill the Treeview
def obtenerDatos():
cursor = conexion.cursor()
cursor.execute("SELECT empresas.empresa, picos.pico, tamano_precio.tamano FROM cilindros, empresas, picos, tamano_precio WHERE empresa_id = empresas.id AND pico_id = picos.id AND tamano_id = tamano_precio.id AND jefesf_id =? ORDER BY cilindros.tamano_id ASC", (validarCi,))
datosConsulta = cursor.fetchall()
return datosConsulta
cursor.close()
cursor.execute("SELECT * FROM jefesf WHERE ci =?", (validarCi,))
Then I use an if to check if there are people with that data registered in the DB
if cursor.fetchall():
ventana3 = Toplevel()
datosConsulta = obtenerDatos()
contador = 0
datosJefes = ttk.Treeview(ventana3, columns=("colum1", "colum2"))
datosJefes.column("#0", width=80)
datosJefes.column("colum1", width=80, anchor=CENTER)
datosJefes.column("colum2", width=80, anchor=CENTER)
datosJefes.heading("#0", text="Empresa")
datosJefes.heading("colum1", text="Pico")
datosJefes.heading("colum2", text="Tamaño")
Here I begin to fill the Treview with the data
for listado in datosConsulta:
datosJefes.insert("", "end", text=listado[0], values=(listado[1], listado[2]))
datosJefes.pack()
This is where I have the problem, what I want to do is to be able to select records from the treview and that those records are saved in a multilist and print them to me by console, but I don't know how
def SeleccinarRegistro():
global listaCilin
global dato1
global dato2
listaCilin = []
dato = datosJefes.item(datosJefes.selection())
datos = list(dato.values())
dato1 = datos[0]
dato2 = datos[2][0]
dato3 = datos[2][1]
I tried with a While loop but it generates an infinite loop, and my idea was every time I press the button the loop runs and saves the elements in the list
while SeleccinarRegistro:
listaCilin.append([dato1, dato2, dato3, validarCi])
print("Empresa: ", dato1)
print("Pico: ", dato2)
print("Tamano: ", dato3)
print(listaCilin)
Button(ventana3, text="Seleccionar", command=SeleccinarRegistro).pack()
By selecting two comboboxes (combined with bind), I would like to extract the ID of a field from Table1 and insert it into Table2. I have no problems extracting a field based on a combobox, but I have problems extracting a field based on 2 comboboxes, because they are combined with each other. The problem is only def id_rounds() function.
I have two comboboxes: one in which I select the name of the "Tournament" and another in which I select the number of Rounds (from 1 to 38 different rounds for each tournament). To choose which tournament the tournament ID must match, I use the combobox combo_Tournaments and function def combo_tournaments; while to choose the number of the Round I use the combobox combo_Rounds and the combo_rounds function. By selecting the Tournament and / or Round, the relevant ID is also automatically entered (as well as the actual data). So each combobox puts in 2 things each, for a total of 4.
Here is the database:
CREATE TABLE "All_Tournament" (
"ID_Tournament" INTEGER,
"Tournament" TEXT,
PRIMARY KEY("Tournament" AUTOINCREMENT)
);
CREATE TABLE "All_Round" (
"ID_Round" INTEGER,
"Number_Round" INTEGER,
"ID_Tournament" INTEGER,
PRIMARY KEY("ID_Round" AUTOINCREMENT),
);
PROBLEM: Currently as I wrote the code of the function def id_rounds(), the ID of the selected Round is saved, but without exact correspondence to the chosen Tournament in the Tournament combobox. The problem is that each Tournament is each made up of 38 different Rounds, therefore in the All_Round table the numbers from 1 to 38 are repeated several times, each corresponding to the Tournament ID. For example Serie A from 1 to 38 Round; Serie B from 1 to 38 rounds; Premier League from 1 to 38 rounds. So I would like to enter the ID of the single Round corresponding to the Tournament (in relation to the tournament), because each tournament has 1 to 38 rounds, so there are many different "1 to 38 rounds" for each tournament.
#Combobox Tournament
lbl_Tournament = Label(root, text="Tournament", font=("Calibri", 11), bg="#E95420", fg="white")
lbl_Tournament.place(x=6, y=60)
combo_Tournaments = ttk.Combobox(root, font=("Calibri", 11), width=30, textvariable=campionato, state="readonly")
combo_Tournaments.place(x=180, y=60)
combo_Tournaments.set("Select")
combo_Tournaments['values'] = combo_tournaments()
combo_Tournaments.bind('<<ComboboxSelected>>', combo_teams)
lbl_Rounds = Label(root, text="Rounds", font=("Calibri", 11), bg="#E95420", fg="white")
lbl_Rounds.place(x=600, y=60)
combo_Rounds = ttk.Combobox(root, font=("Calibri", 11), width=30, textvariable=rounds, state="readonly")
combo_Rounds.place(x=680, y=60)
combo_Rounds.set("Select")
combo_Rounds['values'] = combo_campionati()
combo_Tournaments.bind('<<ComboboxSelected>>', combo_rounds, add=True)
def combo_tournaments():
tournaments = combo_tournaments.get()
cursor.execute('SELECT Tournament FROM All_Tournament')
result=[row[0] for row in cursor]
return result
def id_tournaments():
tournaments = combo_tournaments.get()
cursor.execute('SELECT ID_Tournament FROM All_Tournament WHERE Tournament=?',(tournaments,))
result=[row[0] for row in cursor]
return result[0]
def combo_rounds(event=None):
rounds = combo_rounds.get()
cursor.execute('SELECT Number_Round From All_Round WHERE ID_Tournament')
result=[row[0] for row in cursor]
combo_Rounds['value'] = result
return result
#THE PROBLEM IS HERE
def id_rounds():
rounds = combo_rounds.get()
cursor.execute('SELECT ID_Round FROM All_Round WHERE Number_Round=? AND Tournament=?',(rounds, tournaments))
result=[row[0] for row in cursor]
return result[0]
def combo_teams(event=None):
tournaments = combo_tournaments.get()
cursor.execute('SELECT s.Name_Teams FROM All_Teams s, All_Tournament c WHERE s.ID_Tournament=c.ID_Tournament AND c.Tournament = ?', (tournaments,))
result=[row[0] for row in cursor]
combo_Teams_1['values'] = result
combo_Teams_2['values'] = result
return result
WHAT DO I WANT TO GET? So I would like to obtain for example that: if from the Tournament combobox I select Serie A and then Round 1, in the Results table the ID of Round 1 should be entered but corresponding to Serie A. Or, another example, if from the Tournament combobox I select Serie B and then Round 1, the ID of Round 1 should be entered in the Results table but corresponding to Serie B.
QUESTION: How can I fix the function def id_rounds and which inserts the number of the Round in correspondence (in relation) to the tournament? Currently I only enter the ID of the selected Round in the combobox without matching the championship chosen in the tournament combobox.
Below is the modified code based on my understanding:
def combo_tournaments():
cursor.execute('SELECT Tournament FROM All_Tournament')
result=[row[0] for row in cursor]
return result
def combo_rounds(event=None):
# get all Number_Round for selected tournament
cursor.execute('''
SELECT Number_Round From All_Round r, All_Tournament t
WHERE r.ID_Tournament = t.ID_Tournament AND Tournament = ?''', (campionato.get(),))
result=[row[0] for row in cursor]
combo_Rounds['value'] = result # update combo_Rounds
rounds.set('Select') # reset Rounds selection
return result
def id_rounds(event=None):
# get the ID_Round based on selected tournament and Number_Round
cursor.execute('''
SELECT ID_Round FROM All_Round r, All_Tournament t
WHERE r.ID_Tournament = t.ID_Tournament AND Number_Round = ? AND Tournament = ?''',
(rounds.get(), campionato.get()))
result = cursor.fetchone()
if result:
print(result[0])
return result[0]
return None
...
campionato = StringVar()
rounds = StringVar()
#Combobox Tournament
lbl_Tournament = Label(root, text="Tournament", font=("Calibri", 11), bg="#E95420", fg="white")
lbl_Tournament.place(x=6, y=60)
combo_Tournaments = ttk.Combobox(root, font=("Calibri", 11), width=30, textvariable=campionato, state="readonly")
combo_Tournaments.place(x=180, y=60)
combo_Tournaments.set("Select")
combo_Tournaments['values'] = combo_tournaments()
combo_Tournaments.bind('<<ComboboxSelected>>', combo_rounds)
lbl_Rounds = Label(root, text="Rounds", font=("Calibri", 11), bg="#E95420", fg="white")
lbl_Rounds.place(x=600, y=60)
combo_Rounds = ttk.Combobox(root, font=("Calibri", 11), width=30, textvariable=rounds, state="readonly")
combo_Rounds.place(x=680, y=60)
combo_Rounds.set("Select")
combo_Rounds.bind('<<ComboboxSelected>>', id_rounds)
...
Note that I have used the campionato and rounds (StringVar) to get the selected tournament and Number_Round.
I creating GUI interacting with treeview and I want to get all the value inside the list and show it in treeview window. I have a add button and once I click it, it will work fine. But on the second time, it shows an error Item 1 already exists. It also does not added to the list.
This is my code:
from tkinter import *
from tkinter import ttk
root = Tk()
def add1():
global count
for i in tree_table.get_children():
tree_table.delete(i)
get_name = txt_name.get()
get_ref = txt_ref.get()
get_age = txt_age.get()
get_email = txt_email.get()
data_list.append((get_name, get_ref, get_age, get_email))
for item in data_list:
tree_table.insert(parent='', index='end', iid=count, text=f'{count + 1}', values=(item))
txt_name.delete(0, END)
txt_ref.delete(0, END)
txt_age.delete(0, END)
txt_email.delete(0, END)
count += 1
print(data_list)
tree_table = ttk.Treeview(root)
global count
count = 0
data_list = []
tree_table['columns'] = ("Name", "Reference No.", "Age", "Email Address")
tree_table.column("#0", width=30)
tree_table.column("Name", width=120, anchor=W)
tree_table.column("Reference No.", width=120, anchor=W)
tree_table.column("Age", width=120, anchor=W)
tree_table.column("Email Address", width=120, anchor=W)
headings = ["#0", "Name", "Reference No.", "Age", "Email Address"]
txt_headings = ["No.", "Name", "Reference No.", "Age", "Email Address"]
for i in range(len(headings)):
tree_table.heading(headings[i], text=txt_headings[i], anchor=W)
txt_name = Entry(root, width=20)
txt_name.pack()
txt_ref = Entry(root, width=20)
txt_ref.pack()
txt_age = Entry(root, width=20)
txt_age.pack()
txt_email = Entry(root, width=20)
txt_email.pack()
btn_enter = Button(root, text="Add", width=20, command=add1)
btn_enter.pack()
tree_table.pack()
root.mainloop()
Traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\Python385\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "d:/Code/Cpet5/new.py", line 32, in add1
tree_table.insert(parent='', index='end', iid=count, text=f'{count + 1}', values=(item))
File "C:\Python\Python385\lib\tkinter\ttk.py", line 1366, in insert
res = self.tk.call(self._w, "insert", parent, index,
_tkinter.TclError: Item 1 already exists
How do I refresh the treeview to reflect the changes made in the list?
Quick fix:
Get rid of the iid argument:
tree_table.insert(parent='', index='end', text=f'{count + 1}', values=(item))
But that will create an issue of the No. column getting same value always.
Actual fix:
So the actual problem is your list contains alot of values, you should get rid of those values once you insert it, so the code should be something like:
def add1():
global count
get_name = txt_name.get()
get_ref = txt_ref.get()
get_age = txt_age.get()
get_email = txt_email.get()
data_list.clear() #clear the list
data_list.append((get_name, get_ref, get_age, get_email)) #append to the empty list
for item in data_list:
tree_table.insert(parent='', index='end',iid=count, text=f'{count + 1}', values=(item))
txt_name.delete(0, END)
txt_ref.delete(0, END)
txt_age.delete(0, END)
txt_email.delete(0, END)
count += 1
print(data_list)
This way your clearing whats inside of the list each time and appending new values to list.
With your older code you can see that first time the the list is [('1', '1', '1', '1')] and when the next set of values is appended it becomes [('1', '1', '1', '1'), ('2', '2', '2', '2')] so there is not enough space accommodate all this value in? Anyway this fixes it. Or you could also make a tuple of those inputs and then pass that tuple as the values for treeview without looping, like acw1668 did.
You don't need to clear the treeview before adding new row to it:
def add1():
global count
get_name = txt_name.get()
get_ref = txt_ref.get()
get_age = txt_age.get()
get_email = txt_email.get()
row = (get_name, get_ref, get_age, get_email)
data_list.append(row)
count += 1
tree_table.insert(parent='', index='end', iid=count, text=f'{count}', values=row)
txt_name.delete(0, END)
txt_ref.delete(0, END)
txt_age.delete(0, END)
txt_email.delete(0, END)
print(data_list)
I want to sum values from treeview column no matter if one of the rows is empty, also I want to delete that row when the Sum button is pressed. I wrote a code but I always get this error:
IndexError: string index out of range
This is the code:
from tkinter import*
from tkinter import ttk
myApp = Tk()
myApp.title(" Program ")
TotalEntry=Entry(myApp, width=18)
TotalEntry.grid(row=0,column=1, sticky="e", pady=5)
NewTree= ttk.Treeview(myApp, height=7)
NewTree['show'] = 'headings'
NewTree["columns"]=("1")
NewTree.column("1", width=80, anchor="center")
NewTree.heading("1", text="ID")
item = NewTree.insert("", "end", values=(2))
item = NewTree.insert("", "end", values=(""))
item = NewTree.insert("", "end", values=(6))
NewTree.grid(row=0,column=0)
def SumAllCosts():
for i in NewTree.get_children():
a = NewTree.item(i,"values")[0]
if len(a)==0:
NewTree.delete(i)
SumPreCosts=0.0
for child in NewTree.get_children():
PreCost=round(float(NewTree.item(child,"values")[0]),2)
SumPreCosts += PreCost
TotalEntry.delete(0,"end")
TotalEntry.insert(0,round(SumPreCosts,2))
Sum=Button(myApp,text=" Sum ",command=SumAllCosts)
Sum.grid(row=0,column=2, sticky="w",pady=5)
myApp.mainloop()
If you print type(NewTree.item(i, "values")) and repr(NewTree.item(i, "values")), you can see that this returns
<class 'tuple'> ('2',)
<class 'str'> ''
<class 'tuple'> ('6',)
As you can see, for the 2 and 6 entry, this returns a tuple so you can do NewTree.item(i, "values")[0] to get the first value. However, the empty item is returned as an empty string, so NewTree.item(i, "values")[0] gives the error you describe.
You can change that part of the code to check if NewTree.item(i, "values") is not empty:
for i in NewTree.get_children():
if not NewTree.item(i, "values"):
NewTree.delete(i)
I have Tkinter program that has to add a significant amount of data to the window so I tried to write a for loop to take care of it but since I have to use a string variable for the name of the object that Tkinter is running .insert() on the object. I didn't explain it very well here is the method
def fillWindow(self):
global fileDirectory
location = os.path.join(fileDirectory, family + '.txt')
file = open(location, 'r')
ordersDict = {}
for line in file:
(key, value) = line.split(':', 1)
ordersDict[key] = value
for key in ordersDict:
ordersDict[key] = ordersDict[key][:-2]
for item in ordersDict:
if item[0] == '#':
if item[1] == 'o':
name = 'ordered%s' %item[2:]
right here is the problem line because I have the variable that matches the name of the entry object already created but 'name' is actually a string variable so it gives me the error "AttributeError: 'str' object has no attribute 'insert'"
name.insert(0,ordersDict[item])
here is the entire class. It makes a Tkinter window and fills it with a sort of shipping screen so all the entries are for how many orders of a certain thing are needed. I'm also very new so I know that I do things the long way a lot.
class EditShippingWindow(Tkinter.Toplevel):
def __init__(self, student):
Tkinter.Toplevel.__init__(self)
self.title('Orders')
family = student
## Window Filling
ageGroupLabel = Tkinter.Label(self,text='Age Group')
ageGroupLabel.grid(row=0,column=0)
itemColumnLabel = Tkinter.Label(self,text='Item')
itemColumnLabel.grid(row=0, column=1)
costColumnLabel = Tkinter.Label(self,text='Cost')
costColumnLabel.grid(row=0, column=2)
orderedColumnLabel = Tkinter.Label(self,text='Ordered')
orderedColumnLabel.grid(row=0, column=3)
paidColumnLabel = Tkinter.Label(self,text='Paid')
paidColumnLabel.grid(row=0, column=4)
receivedColumnLabel = Tkinter.Label(self,text='Received')
receivedColumnLabel.grid(row=0, column=5)
#Item Filling
column1list = ['T-Shirt (2T):$9.00', 'T-Shirt (3T):$9.00', 'T-Shirt (4T):$9.00',
'Praise Music CD:$10.00', ':', 'Vest L(Size 6):$10.00', 'Vest XL(Size 8):$10.00',
'Hand Book (KJ/NIV):$8.75', 'Handbook Bag:$6.00', 'Memory CD (KJ/NIV):$10.00',
':', 'Vest L(size 10):$10.00', 'Vest XL(Size 12):$10.00', 'Hand Glider (KJ/NIV/NKJ):$10.00',
'Wing Runner (KJ/NIV/NKJ):$10.00', 'Sky Stormer (KJ/NIV/NKJ):$10.00', 'Handbook Bag:$5.00',
'Memory CD (S/H/C):$10.00', 'Hand Glider Freq. Flyer:$8.00', 'Wing Runner Freq. Flyer:$8.00',
'Sky Stormer Handbook:$8.00' , ':', 'Uniform T-Shirt Size (10/12/14):$13.00',
'Uniform T-Shirt Size(10/12/14):$13.00', 'Uniform T-Shirt(Adult S / M / L / XL):$13.00',
'3rd & 4th Gr. Book 1 (KJ / NIV / NKJ):$8.75', '3rd & 4th Gr. Book 2 (KJ / NIV / NKJ):$8.75',
'4th & 5th Gr. Book 1 (KJ / NIV / NKJ):$8.75', '4th & 5th Gr. Book 2 (KJ / NIV / NKJ):$8.75',
'Memory CD 3rd & 4th Gr. Book (1/2):$10.00', 'Drawstring Backpack:$5.50']
column1num = 1
for item in column1list:
num = str(column1num)
(title, price) = item.split(':')
objectName1 = 'column1row' + num
objectName1 = Tkinter.Label(self,text=title)
objectName1.grid(row=column1num, column=1)
objectName2 = 'column1row' + num
objectName2 = Tkinter.Label(self,text=price)
objectName2.grid(row=column1num, column=2)
column1num += 1
#Ordered Paid Recieved Filler
for i in range(32):
if i == 11 or i == 22 or i == 0 or i == 5:
pass
else:
width = 10
# First Column
title1 = 'ordered' + str(i)
self.title1 = Tkinter.Entry(self,width=width)
self.title1.grid(row=i,column=3)
#self.title1.insert(0, title1)
#Second
title2 = 'paid' + str(i)
self.title2 = Tkinter.Entry(self,width=width)
self.title2.grid(row=i,column=4)
#self.title2.insert(0, title2)
#Third
title3 = 'received' + str(i)
self.title3 = Tkinter.Entry(self,width=width)
self.title3.grid(row=i,column=5)
#self.title3.insert(0, title3)
## Methods
def fillWindow(self):
global fileDirectory
location = os.path.join(fileDirectory, family + '.txt')
file = open(location, 'r')
ordersDict = {}
for line in file:
(key, value) = line.split(':', 1)
ordersDict[key] = value
for key in ordersDict:
ordersDict[key] = ordersDict[key][:-2]
for item in ordersDict:
if item[0] == '#':
if item[1] == 'o':
self.name = 'ordered%s' %item[2:]
self.name.insert(0,ordersDict[item])
fillWindow(self)
It looks like you have a conceptual error there: inside this method, the variable "name" does not exist up to the last line on the first listing. Then it is created, and points to an ordinary Python string -- if you are using a "name" variable elsewhere on your class that variable does not exist inside this method.
For an easy fix of your existing code, try calling the variable as "self.name" instead of just name where it is created, and on your last line in this method use:
self.name.insert(0,ordersDict[item]) instead.
The self. prefix will turn your variable into an instance variable, which is shared across methods on the same instance of the class.
On a side note, you don' t need even the dictionary much less three consecutive for loops on this method, just insert the relevant values you extract from "line" in your text variable.