Show percentage and label - python

I'm trying to show the label and the percentage in the Qchart but it show me only one of them
Is there a way to show both of them
This is my function that run the QtChart
def charts_jr_acte(self):# pushButton_123
rightseries = QPieSeries()
rightseries.setLabelsVisible(True)
rightseries.setLabelsPosition(QPieSlice.LabelInsideHorizontal)
for C_acte, montant in rows:
rightseries.append(C_acte, montant)
slice = QPieSlice()
slice = rightseries.slices() [2]
slice.setExploded(True)
slice.setPen(QtGui.QPen(Qt.darkBlue))
for slice in rightseries.slices():
slice.setLabel("{:.2f}%".format(100 * slice.percentage()))
rightchart = QChart()
rightchart.createDefaultAxes()
rightchart.addSeries(rightseries)
rightchart.setTitle("total journalier de chaque Acte")
rightchart.setAnimationOptions(QChart.SeriesAnimations)
rightchart.legend().setVisible(True)
rightchart.legend().setAlignment(Qt.AlignBottom)
rightchart.legend().markers(rightseries)[1].setLabel(lab)
rightseries.setLabelsVisible()
rightseries.setLabelsPosition(QtChart.QPieSlice.LabelInsideHorizontal)
self.graphicsView_4.setChart(rightchart)
`
and this is an example of the result

i find a way to make it work
def charts_jr_acte(self):# pushButton_123
rightseries = QPieSeries()
rightseries.setLabelsVisible(True)
for C_acte, montant in rows:
rightseries.append(C_acte, montant)
slice = QPieSlice()
slice = rightseries.slices() [2]
slice.setExploded(True)
slice.setPen(QtGui.QPen(Qt.darkBlue))
for slice in rightseries.slices():
slice.setLabelVisible()
oldLabel=slice.label()
slice.setLabel((oldLabel+": %.1f%%" %(slice.percentage()*100) ))
rightchart = QChart()
rightchart.createDefaultAxes()
rightchart.addSeries(rightseries)
rightchart.setTitle("total journalier de chaque Acte")
rightchart.setAnimationOptions(QChart.SeriesAnimations)
rightchart.legend().setVisible(True)
self.graphicsView_4.setChart(rightchart)
this how it look like

Related

Formula Cell Wont Update Openpyxl

I fill the cells I need, then I set the total formula. It works right in one column, with normal numbers, but in the column with times (hh:mm:ss) the total cell is not being updated. If i manually change a cell, then it will be computed to the total. I dont know why this happens.
excel sheet:
The G column total cell (Qt_horas) has the formula, but it does not apply via openpyxl
the code:
df = pd.read_excel('Status Report Coagril 20-04-2022.xlsx', 'Acompanhamento Solics. Projeto')
planilha = load_workbook('Status Report Coagril 20-04-2022.xlsx', data_only=True)
ws = planilha['Acompanhamento Solics. Projeto']
start = 17
for i, nr_solic in enumerate(sols_filhas):
query_sol = f"select nr_solicitacao, ds_assunto, st_solic, ds_status from solicservico_v2 a, statussolic b where a.nr_solicitacao = {nr_solic} and a.st_solic = b.cd_status"
query = db.query(query_sol)
# atribuo as variaveis que vieram da query do banco
nr_solicitacao = query['nr_solicitacao'].values[0]
ds_assunto = query['ds_assunto'].values[0]
ds_status = query['ds_status'].values[0]
horas_realizadas = formata_horas(db.query(f'SELECT retorna_min_realizados_solic({nr_solicitacao})/60 minutos FROM DUAL')['minutos'].values[0])
# verifico se alguma das células que estou preenchendo, foi erroneamente mergeada com as coluna E ou F, e então desfaço o merge
e_merged = f'B{start+i}:E{start+i}'
f_merged = f'B{start+i}:F{start+i}'
lista = str(ws.merged_cells).split(' ')
if e_merged in lista:
ws.unmerge_cells(e_merged)
if f_merged in lista:
ws.unmerge_cells(f_merged)
# insiro uma nova linha, a não ser que seja o primeiro registro, pois já há uma linha em branco
# if i != 0:
# ws.insert_rows(start+i)
ws.insert_rows(start+i)
# preenche_linha(ds_assunto, 'B', start+1, 'left', 'no_right', ws)
# preenche_linha(None, 'C', start+1, 'left', 'no_left', ws)
# preenche_linha(nr_solicitacao, 'D', start+1, 'center', 'total', ws)
# preenche_linha(ds_status, 'E', start+1, 'center', 'total', ws)
# preenche_linha(1, 'F', start+1, 'center', 'total', ws)
# preenche_linha(horas_realizadas, 'G', start+1, 'center', 'total', ws)
# preenche_linha('Maxicon', 'H', start+1, 'center', 'total', ws)
ws[f'B{start+i}'] = ds_assunto
ws[f'B{start+i}'].alignment = Alignment(horizontal='left')
ws[f'B{start+i}'].border = aplica_borda_sem_direita()
ws[f'C{start+i}'].border = aplica_borda_sem_esquerda()
ws[f'D{start+i}'] = nr_solicitacao
ws[f'D{start+i}'].alignment = Alignment(horizontal='center')
ws[f'D{start+i}'].border = aplica_borda_total()
ws[f'E{start+i}'] = ds_status
ws[f'E{start+i}'].alignment = Alignment(horizontal='center')
ws[f'E{start+i}'].border = aplica_borda_total()
ws[f'F{start+i}'] = 1
ws[f'F{start+i}'].alignment = Alignment(horizontal='center')
ws[f'F{start+i}'].border = aplica_borda_total()
ws[f'G{start+i}'].number_format = 'h:mm:ss'
ws[f'G{start+i}'] = horas_realizadas
ws[f'G{start+i}'].border = aplica_borda_total()
ws[f'G{start+i}'].alignment = Alignment(horizontal='center')
ws[f'H{start+i}'] = 'Maxicon'
ws[f'H{start+i}'].alignment = Alignment(horizontal='center')
ws[f'H{start+i}'].border = aplica_borda_total()
last_sol = len(sols_filhas) + start - 1
ws[f'F{last_sol+1}'] = f'=SUM(F{start}:F{last_sol})'
ws[f'G{last_sol+1}'].number_format = 'h:mm:ss'
ws[f'G{last_sol+1}'] = f'=SUM(G{start}:G{last_sol})'
ws[f'F{last_sol+1}'].alignment = Alignment(horizontal='center')
ws[f'G{last_sol+1}'].alignment = Alignment(horizontal='center')
planilha.save('teste.xlsx')````
[1]: https://i.stack.imgur.com/e2xOV.png
I would say that even though you are setting the cell format to 'h:mm:ss', Excel does not recognise the cells as being time values until a cell is updated. However the cell format you're using will result in an incorrect resultE.g. those values that do not conform with 'normal time' will be reset to 24hr time as the format assumes the highest value to be 23:59:59. Anything larger like 197:06:00 and 29:32:00 are going to be converted to 5:06:00 and 5:32:00 respectively.
You should use the format
'[h]:mm:ss'
(where 'h' is in square brackets) to allow hours above 24.
Even given a different format you may still have the same issues summing the values as
'=SUM(GX:GY)'
if there are and you want/need to do the sum in Excel it might work better to use the long hand like
'=SUM(GA+GB+GC+GD+...)'
Otherwise use python to change the format e.g. change everything to seconds and sum as numerical data (Excel can then display in format as required) or just do the summing in python writing all values to Excel.

python TypeError: 'int' object does not support item assignment python

this issue appear when I put promedios[x] = float(punteos / 3), if suppose to x is in for outside have a int value like possition. I modified the code with the new changes
def alumno(nombre, apellido):
print('Nombre: ', nombre, 'Apellido: ', apellido)
def promedio(a,b,c):
promedio1 = int(a+b+c)/3
#return promedio1
print(promedio1)
nombre = input('ingrese nombre: ')
apellido = input('ingrese apellido: ')
alumno(nombre,apellido)
print()
#promedio(1,2,3)
print('Ingrese los punteos de las Materias:')
punteo = 0
materias = 5
for x in range(0, materias):
punteos = 0
notas = 3
promedio1 = 0
promedios = []
xx = 1
for y in range(0, notas):
punteo = int(input("Ingrese punteo de la Materia "+str(x+1)+" punteo "+str(y+1)+": "))
punteos = int(punteos + punteo)
promedio1 = float(punteos/3)
promedios.append(promedio1)
print('El promedio de la materia ',x+1,' es ',promedio1)
print(promedios[x])
As long as you have done promedios = 0 and no longer modify the variable promedios before the line of code promedios[x] = float(punteos / 3), promedios is an int at that line.
However, doing promedios[x] = ... calls the __setitem__ method of variable promedios, which is of type int and of course does not support such item assignment.
Types like list, dict support item assignment, by the way.
You need to start with an empty list:
promedios = []
And then append to it:
promedios.append(float(punteos / 3))

Generating a table with docx from a dataframe in python

Hellow,
Currently I´m working in a project in which I have to generate some info with docx library in python. I want to know how to generate a docx table from a dataframe in order to have the output with all the columns and rows from de dataframe I've created. Here is my code, but its not working correctly because I can´t reach the final output:
table = doc.add_table(rows = len(detalle_operaciones_total1), cols=5)
table.style = 'Table Grid'
table.rows[0].cells[0].text = 'Nombre'
table.rows[0].cells[1].text = 'Operacion Nro'
table.rows[0].cells[2].text = 'Producto'
table.rows[0].cells[3].text = 'Monto en moneda de origen'
table.rows[0].cells[4].text = 'Monto en moneda local'
for y in range(1, len(detalle_operaciones_total1)):
Nombre = str(detalle_operaciones_total1.iloc[y,0])
Operacion = str(detalle_operaciones_total1.iloc[y,1])
Producto = str(detalle_operaciones_total1.iloc[y,2])
Monto_en_MO = str(detalle_operaciones_total1.iloc[y,3])
Monto_en_ML = str(detalle_operaciones_total1.iloc[y,4])
table.rows[y].cells[0].text = Nombre
table.rows[y].cells[1].text = Operacion
table.rows[y].cells[2].text = Producto
table.rows[y].cells[3].text = Monto_en_MO
table.rows[y].cells[4].text = Monto_en_ML

Python tkinter - auto click on selected item from Treeview

I have a treeview widget that displays a simple list from a table.
I want to automatically highlight one of the items on the list. (this works perfectly).
Now, I want this item to automatically receive a mouse click (without any action from the user). according to the documentation, use the command Rec_list.event_generate ('<ButtonRelease-1>' .format (button-1), when = "now")
but without results.
# coding:utf-8
#version 3.x python
from tkinter import *
from tkinter.ttk import *
from tkinter import ttk
def Load_Recette_Contenu():
Load_Recette = tk.Toplevel()
Load_Recette.title("Ouvrit une recette SAF")
Load_Recette.geometry("325x178+0+0")
Load_Recette.resizable(width=False, height=False)
# Fenêtre verrouillée
Load_Recette.attributes("-toolwindow", 1)
# Supprime les boutons Réduire/Agrandir
Load_Recette.attributes("-topmost", 1)
# au premier plan
# ==================================================
# TreeView
# ==================================================
# --- Insertion Table Nom HV dans TreeView
def DisplayData():
for i in Recette_DB_BackEnd.loadRecord():
# print("Nom de la recette --> ", i[0])
Rec_list.insert('', 'end', text=i[0], values=(i[0]))
# --- Insertion Scrollbar
scrollbar_y = Scrollbar(Recette_TreView, orient='vertical') # Ascenseur Vertical
scrollbar_y.place(x=299, y=0, height=169)
Rec_list = ttk.Treeview(Recette_TreView, selectmode="browse", columns=(1), show="headings", yscrollcommand=scrollbar_y.set)
# --- En-tête
Rec_list.heading('#1', text="Recettes")
# --- Largeur Colonnes
Rec_list.column('#1', width=300, minwidth=40, stretch=OFF)
Rec_list.place(x=0, y=0, width=301, height=168)
scrollbar_y.config(command=Rec_list.yview) # Ascenseur Vertical
DisplayData()
def selectionItem(a):
# === [Sélection - Widget Treeview] ===
curItem = Rec_list.focus()
Liste = Rec_list.item(curItem)["values"]
# print("winfo_name()", Rec_list.winfo_name()) # ID widget Treeview -- Exemple : winfo_name() !treeview
# print("Liste - TreeView - Recette sélectionnée", Liste) # Affiche la sélection contenu de la liste
# print("Liste - TreeView - Colonne Nom -->", Liste[0])
# for child in Rec_list.get_children(): # Listing du contenu de la Treeview -- Exemple : ['Recette_2020.05_8_30.5_NoName']
# print(Rec_list.item(child)["values"])
# print("Rec_list.item(curItem)[","values","][0] ", Rec_list.item(curItem)["values"][0]) # Affiche Nom recette depuis Treeview -- Exemple : Recette_2020.05_8_30.5_NoName
# print("Rec_list.get_children()", Rec_list.get_children()) # iid -- Renvoie un tuple des valeurs iid des enfants de l'élément spécifié par l'argument élément. S'il est omis, vous obtenez un tuple contenant les valeurs iid des éléments de niveau supérieur. --- exemple : Rec_list.get_children() ('I001', 'I002', 'I003', 'I004')
# print("Rec_list.get_children()[0]", Rec_list.get_children()[0])
# print("Rec_list.get_children()", Rec_list.get_children([Rec_list.item(curItem)["values"][0]])) ????????????????????
z = -1
for child in Rec_list.get_children():
z = z +1
time.sleep(1)
Rec_list.update()
Rec_list.selection_set(Rec_list.get_children()[z])
# Rec_list.event_generate('<ButtonRelease-1>'.format(button-1), when="now")
Rec_list.focus_force()
Rec_list.focus_set()
Rec_list.focus(Rec_list.get_children()[z])
Rec_list.update()
# -- Identifie le type de bouton activé --
# un bouton pressé(event.type = 4)
# un bouton relaché(event.type = 5)
# un bouton pressé en mouvement(event.type = 6)
print("\ntype :", a.type)
# -- Identifie quel bouton pressé --
# clic gauche(Bouton 1): event.num = 1
# clic droit(Bouton 3): event.num = 3
print("num :", a.num)
# Load_Recette.update()
# Rec_list.event_generate('<ButtonPress-1>')
# Load_Recette.update()
# ==================================================
# Evénement Treeview
# ==================================================
# via souris
Rec_list.bind('<ButtonRelease-1>', selectionItem) # Le bouton de la souris a été relâché
how to activate a mouse click without user intervention?
Thank you for your time, have good day
Auto Selection Item
This is a slightly nonprofessional route, but using a library such as py-game can automatically click or select with the mouse, you would have to take in to account screen resolution though. You can also try to see if there is a property to auto-select, check the Tkinter reference guide for help, Link 1
i find solution
import tkinter as tk
import tkinter.ttk as ttk
import time
tree = ttk.Treeview()
for i in range(10):
iid = tree.insert('', 'end', text=i)
tree.pack()
def event_test(iid):
t['text'] = iid
print("iid", iid)
def move_bottom():
iid = tree.get_children('')[-1]
time.sleep(1)
if iid != tree.focus():
iid = tree.get_children('')[5]
tree.focus(iid)
tree.selection_set(iid)
print("iid", iid)
tree.event_add('<<Declenche>>', '<ButtonRelease-1>')
tree.after(1000, lambda: tree.event_generate('<<Declenche>>'))
tree.bind('<<Declenche>>', event_test(iid))
t = tk.Label()
t.pack()
tk.Button(text='move', command=move_bottom).pack()
tree.mainloop()
To automate the selection I found this solution: in insert for loop where the data is from a table of a database, I use 1 particular db-data as value (better an unique id). I get the iid with get_children method using the loop index. In the for I insert data into a dictionary where the key is the iid and the value is the value (unique data) form the db.
If the goal to change data in the row and send that back into the database, you can make a query selection to find the first unchanged row, and select only the unique id, unique data of this row (or use the main autoincremented rowid). Use that id for having the iid of that row, than make focus and selection with that iid. After the binding that selection to an event you can run that calling event to run your method without clicking on any row.
def calling(event):
selectedRow = tree.item(tree.focus())
datas = selectedRow['values']
var1 = datas[0]
var2 = datas[1]
yourMethod(var1, var2)
def keyGetter(val, lib):
for key, value in lib.items():
if val == value:
return key
return "key doesn't exist"
index = 0
iidLibrary = dict()
for row in rows:
tree.insert("", index, values = (row[0], row[1], row[2))
iid = tree.get_children()[index]
iidLibrary[iid] = row[3]
curs.execute(
"SELECT id_of_row FROM table WHERE something=? ORDER BY rowid ASC LIMIT 1", (variable, )
firstUnclosed = curs.fetchall()
iidActual = keyGetter(firstUnclosed[0][0], iidLibrary)
tree.focus(iidActual)
tree.selection_set(iidActual)
tree.bind('<<TreeviewSelect>>', calling)

aligning, spacing in python 3

What can I do to align all columns in this code?, is that correct or...?
import urllib.request
from re import findall
def determinarLlegadas(numero):
llegadas = urllib.request.urlopen("http://...")
llegadas = str (llegadas.read())
llegadas = findall ('<font color="Black" size="3">(.+?)</font>',llegadas)
print ('\t','VUELO ','\t','AEROLINEA','\t','PROCEDENCIA','\t','FECHA ','\t',' HORA ','\t','ESTADO','\t','PUERTA')
a = 0
numero = numero * 7
while numero > a:
print ('\t',llegadas[a+0],'\t',llegadas[a+1],'\t',llegadas[a+3],'\t',llegadas[a+3],'\t',llegadas[a+4],'\t',llegadas[a+5],'\t',llegadas[a+6])
a = a + 7
Don't use tabs, use string formatting.
...
print("{:12}{:12}{:12}{:12}{:12}{:12}{:12}".format(
"VUELO","AEROLINEA","PROCEDENCIA","FECHA","HORA","ESTADO","PUERTA"))
print("{:12}{:12}{:12}{:12}{:12}{:12}{:12}".format(*llegadas))
Change the 12 to the maximum field size for each column, and you're golden.
In fact, though it's less readable:
COLSIZE = 12
# Maybe COLSIZE = max(map(len,llegadas))+1
NUMCOLS = 7
formatstring = "{}{}{}".format("{:",COLSIZE,"}")*NUMCOLS
# {:COLSIZE}*NUMCOLS
headers = ["VUELO","AEROLINEA","PROCEDENCIA","FECHA","HORA","ESTADO","PUERTA"]
print(formatstring.format(*headers))
print(formatstring.format(*llegadas))

Categories

Resources