PYSIMPLEGUI - Window not working properly - python

I'm creating a GUI and I had an issue. My GUI is supposed to get the user's ID and then show him a button to direct him to another window with some tutorials. If the user has already watched all the tutorials, an input box will appear asking if he wants to watch any tutorial again, if he refuses it (by typing "N") the window will be cleared for another user put his ID.
The code is working, but I noticed that when the user has already watched all tutorials and then refuses to watch again, if the next user has already watched all tutorials too the code doesn't work.
Notice that the input box clears it self, when it was supposed to make the same thing it did in the first picture.
Some curious fact is that if i put the ID of some user that didn't finish the tutorials, it will work fine. And if I put the ID of someone who finished, after puting the ID of someone who didn't, it will work again.
Here is the code, could somone help me?
import pandas as pd
import os
import PySimpleGUI as sg
from window3 import window3
from window2 import window2
from window4 import window4
users_path = r"D:\Users\raulc\Documents\AMBIENTES\TESTE\21 - Ilha de treinamento\Users.csv"
watched_videos_path = r"D:\Users\raulc\Documents\AMBIENTES\TESTE\21 - Ilha de treinamento\watched_videos.csv"
# caminho para a pasta dos videos da 111
path_111 = "D:\\Users\\raulc\\Documents\\AMBIENTES\\videos\\111"
# caminho para a pasta dos videos da 113
path_113 = "D:\\Users\\raulc\\Documents\\AMBIENTES\\videos\\113"
# variavel que armazena o nome dos arquivos que estao na 111
p111 = os.listdir(path_111)
# variavel que armazena o nome dos arquivos que estao na 113
p113 = os.listdir(path_113)
# verifica se o usuario ja esta registrado no banco de dados
def is_registered(ID): #OK
df = read_any_csv(users_path)
x = df.loc[df["ID"] == ID]
if x.empty:
return False
else:
return True
# faz o cadastro do usuario
def register(ID,name,section): # OK
global users_df # need it to add to external variable
# com esse "global" nao precisa ler o csv de novo
data = pd.DataFrame({'NAME': [name], 'ID': [ID], 'SECTION': [section]})
users_df = pd.concat([users_df, data]) # <-- add to original `users_df`
users_df.to_csv(r"D:\Users\raulc\Documents\AMBIENTES\TESTE\21 - Ilha de treinamento\Users.csv", index=False)
# mostrar os videos ja assistidos
def already_watched(ID): #OK
df = read_any_csv(watched_videos_path)
videos = df.loc[df["ID"] == ID,"LINK"]
return videos
# retorna os links que nao foram assistidos ainda
def videos_to_watch(section,ID): #OK
list_already_watched = already_watched(ID).tolist()
if section == 111:
list_to_watch = set(p111)-set(list_already_watched)
elif section == 113:
list_to_watch = set(p113)-set(list_already_watched)
elif section == 000:
list_to_watch = []
return list(list_to_watch)
# retorna setor do usuario
def current_user_section(df,ID):
current_user = df.loc[df["ID"] == ID]
section = int(current_user["SECTION"])
return section
# retorna se a lista de videos a serem assistidos esta vazia ou nao
def is_list_empty(list,section,ID):
list = videos_to_watch(section,ID)
length = len(list)
if length == 0:
return True
else:
return False
# retorna o nome do usuario
def current_user_name(df,ID):
current_user = df.loc[df["ID"] == ID]
name = current_user["NAME"].to_string(index = False)
return name
# retorna os dados do usuario -> nao da para ser essa funcao direto, pois ai o python nao consegue converte o section para int
def current_user_data(df,ID):
name = current_user_name(df,ID)
section = current_user_section(df,ID)
return name,section
# faz a funcao read_csv do pandas
def read_any_csv(path): #OK
df = pd.read_csv(path)
return df
def window():
global users_df
# Definindo o fundo da tela como preto
sg.theme('Black')
# Declarando o logo da mercedes
myImg = sg.Image(filename='logo_meca_pret.png',size=(200,200))
# Declarando os outputs
output = sg.Text(font=("Arial",20),key="output")
output2 = sg.Text(font=("Arial",20),key="output2")
output3 = sg.Text(font=("Arial",20),key="output3")
layout = [
[myImg,sg.Text('PROGRAMA DE TREINAMENTOS',font=("Arial",60),justification="center")],
[sg.Text("Passe o cracha no leitor: ",font=("Arial",20)),sg.InputText(size=(60),key="ID")],
[sg.Text("Escreva seu nome: ",font=("Arial",20),visible=False,key="NAMETEXT"),sg.InputText(size=(60),visible=False,key="NAME")],
[sg.Text("Digite seu setor(111/112/113): ",font=("Arial",20),visible=False,key="SECTIONTEXT"),sg.Input(size=(5),visible=False,key="SECTION")],
[sg.Button('SubmitData', visible=False)],
[output],
[output2],
[output3,sg.InputText(size=(1),key="w_a",visible=False)],
[sg.Text("CLIQUE AQUI E FECHE A JANELA",font=("Arial",20),visible=False,key="BOTAOERROR1"),sg.Text("CLIQUE NO BOTAO PARA ABRIR AS TELAS DOS TUTORIAIS",font=("Arial",20),visible=False,key="BOTAOW3"),sg.Button("W3",visible=False)],
[sg.Text("CLIQUE NO BOTAO PARA ASSISTIR ALGUM TUTORIAL NOVAMENTE",font=("Arial",20),visible=False,key="BOTAOW5"),sg.Button("W5",size=(5),visible=False)],
[sg.Button('Submit', visible=False, bind_return_key=True)],
#[sg.Button("ERROR1",visible=False)],
]
window = sg.Window('PROGRAMA DE TREINAMENTOS MERCEDES BENZ', layout,element_justification="center").Finalize()
window.Maximize()
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
#print('You entered ', values[0])
if event == 'Submit':
ID = values["ID"]
ID = ID.upper()
if is_registered(ID) == True:
if ID == "X":
name,section = current_user_data(users_df,ID)
window["BOTAOERROR1"].update(visible=True)
#window["ERROR1"].update(visible=True)
window["W3"].update(visible=True)
else:
name,section = current_user_data(users_df,ID)
output.update(f"Ola, {name}, bem vindo ao programa de treinamento Mercedes Benz Brasil!\n")
videos = videos_to_watch(section,ID)
if is_list_empty(videos,section,ID) == True:
output2.update("Nao ha novos tutoriais disponiveis.")
output3.update("Deseja assistir algum tutorial novamente (S/N)?")
window['w_a'].update(visible = True)
w_a = values["w_a"]
if w_a == "s" or w_a == "S":
# abre a tela com todos os tutoriais da pasta daquela secao
window2(ID,section)
window.find_element("ID").update("")
window.find_element("output").update("")
window.find_element("output2").update("")
window.find_element("output3").update("")
window.find_element("w_a").update("")
window['w_a'].update(visible = False)
if w_a == "n" or w_a == "N":
# usa esses comandos para limpar a tela, para que um novo usuario use
window.find_element("ID").update("")
window.find_element("output").update("")
window.find_element("output2").update("")
window.find_element("output3").update("")
window['w_a'].update(visible = False) # deixa o input do w_a invisivel de novo
else:
# se tiverem videos a serem assistidos abrir a WINDOW3
window["BOTAOW3"].update(visible = True)
window["W3"].update(visible = True)
if section == 113:
folder = p113
elif section == 111:
folder = p111
if len(videos_to_watch(section,ID)) != len(folder):
window["BOTAOW5"].update(visible = True)
window["W5"].update(visible=True)
else:
window["NAMETEXT"].update(visible = True)
window["NAME"].update(visible = True)
window["SECTIONTEXT"].update(visible = True)
window["SECTION"].update(visible = True)
window["SubmitData"].update(visible = True)
if event == "W5":
window2(ID,section)
# if event == "ERROR1":
# window3(ID,section)
# window.find_element("ID").update("")
# window['BOTAOERROR1'].update(visible=False)
# window['ERROR1'].update(visible=False)
if event == 'SubmitData' :
name = values["NAME"]
name = name.title()
section = values["SECTION"]
output.update(f"Ola, {name}, bem vindo ao programa de treinamento Mercedes Benz Brasil!\n")
register(ID,name,section)
users_df = pd.read_csv(users_path)
window["BOTAOW3"].update(visible = True)
window["W3"].update(visible = True)
if event == "W3":
window3(ID,section)
window.find_element("ID").update("")
window.find_element("output").update("")
window.find_element("output2").update("")
window.find_element("output3").update("")
window.find_element("w_a").update("")
window["W3"].update(visible = False)
window["BOTAOW3"].update(visible = False)
window["NAME"].update(visible = False)
window["SECTION"].update(visible = False)
window["NAMETEXT"].update(visible = False)
window["SECTIONTEXT"].update(visible = False)
window["SubmitData"].update(visible = False)
window["W5"].update(visible = False)
window["BOTAOW5"].update(visible = False)
window["BOTAOERROR1"].update(visible=False)
window.close()
users_df = pd.read_csv(users_path)
watched_videos_df = pd.read_csv(watched_videos_path)
window()

Related

delete an element of a tuple within a list [Python, Tuples, Lists]

I am creating a menu for a billing program with tuples inside lists, how would you do to delete a data requested by the user deleting all its values?
menu = """
(1) Añadir Cliente
(2) Eliminar Cliente
(3) Añadir Factura
(4) Procesar facturacion del mes
(5) Listar todos los clientes
(6) Terminar
"""
lista_nom =[]
list_borra2 = []
ventas = []
while True:
print(menu)
opc = input("Escriba una opcion: ")
opc = int(opc)
if opc == 1:
nombre = input("Escribe el nombre del cliente: ")
cif = input('Escribe el cif de cliente: ')
direccion = input("Escribe el direccion de cliente: ")
lista_nom1 = (nombre,cif,direccion)
lista_nom.append(lista_nom1)
print(lista_nom)
#print(lista_nom1)mismo dato en tupla
if opc == 2:
nombre = input('Escriba el nombre del cliente a borrar: ')
for nombre in lista_nom[0]:
lista_nom.remove[(nombre)]
else:
print('No existe el cliente con el nombre', nombre)
# for nom in range(len(lista_nom)):
# for eli in range(len(lista_nom[nom])):
# if lista_nom[nom][eli][0] == nombre:
# del lista_nom[nom:nom+1]
# print(lista_nom)
I have tried to access the element with nested for but it simply does nothing.
try to create a new list to store the deleted data and then install it in the first list with the main values to be deleted
# list_borra2.append(nombre)
# for nom in range(len(lista_nom)):
# for eli in range(len(lista_nom[nom])):
# if lista_nom[nom][eli][0] == nombre:
# del lista_nom[nom:nom+1]
# print(lista_nom)
# lista_nom.remove(nombre)
# list_borra2 += lista_nom
# # print(list_borra2)
# print(list_borra2)
Instead of deleting an element, what is not possible inside of tuples, you could define a new tuple by doing
nom_remove = lista_nom[:nom] + lista_nom[(nom+1):]
At the end I resolved the problem with this, like the other guy tell me the tuples are immutable so I need to go inside the list and i can access to the tuple:
if opc == 2:
nombre = input('Escriba el nombre del cliente a borrar: ')
vivo = 0
for kilo in ventas:
vivo = ventas[kilo].count(nombre)
if vivo == 0:
for nom in range(len(lista_nom)):
if lista_nom[nom].count(nombre)>0:
del lista_nom[nom:nom+1]
print(lista_nom)
break

manage memory allocation exemple project

so i have this script but i dont know how it worsk can someone please explain it to me , all what i know is that we have two types pf used super user and normal user each one got many taskss
that we excecute after extracting from a file.txt
# Permet de mieux gérer le typing (définition des types lors de la signature fonction)
from future import annotations
# Permet de créer des classes héritant d'énum pour réaliser des énumérations
from enum import Enum
# Gère le multithreading
import threading
# Mise en pause du programme via time.sleep()
import time
# Lecture de la mémoire utilisée
import os, psutil
# Interface graphique
import turtle
import tkinter as tk
from tkinter import ttk
# Shuffle permet de mélanger une liste (utilisé pour la liste des story)
from random import shuffle
__FILENAME__ = "stories.txt"
__KO_SIZE_BYTE__ = 1024
__TIME_TASK_S__ = 5
__NUMBER_BLOCKS_BY_TASK__ = 5
# Booléen permettant de savoir si un super utilisateur a pris la main (mise en pause automatique des utilisateurs normaux)
is_locked_for_super_user = False
### Définition de la classe Block ###
# number_of_block : Nombre de block alloué
# state : status du block (Block.State.FREE ou Block.State.BUSY)
# data : data que le block va stocker (story)
# next_block : reférence du prochaine block
class Block:
_SIZE_ = 512 * __KO_SIZE_BYTE__
class State(Enum):
FREE = 0
BUSY = 1
def __init__(self, number_of_blocks : int, state : Block.State, data : str, next_block : Block = None):
self.number_of_blocks = number_of_blocks
self.state = state
self.data = bytearray(data, encoding="utf-8")
self.data.extend(bytearray(int((Block._SIZE_ * number_of_blocks )- len(data)), ))
self.next_block = next_block
def add(self,next_block : Block, index : int = 1) -> int:
if self.next_block:
return self.next_block.add(next_block, index + 1)
else:
self.next_block = next_block
return index
### Définition d'une classe MemoryBlock qui représente une liste chainée ###
# block : premier block de la liste chainée
class MemoryBlock:
def __init__(self, block : Block = None ):
self.block = block
def __getitem__(self, key):
if key == 0:
return self.block
item = self.block.next_block
for _ in range(1, key):
item = item.next_block
return item
def add(self, block : Block) -> int:
# manage empty block
if not self.block:
self.block = block
return 0
return self.block.add(block)
def remove(self, key):
if key == 0:
self.block = self.block.next_block
else:
self[key - 1].next_block = self[key].next_block
def size(self) -> int:
if not self.block:
return 0
size = 1
current_block = self.block
while current_block.next_block:
current_block = current_block.next_block
size+= 1
return size
### Classe Task ###
# lib_task : Libellé de la tache
# time_task : Temps d'éxécution de la tache en seconde
# mem_task : taille allouée à la tache
# level_task : Priorité de la tache (Task.Priority.HIGH ou Task.Priority.LOW)
# state_task : Etat de la tache (Task.State.ACTIVE ou Task.State.SLEEPING)
# treeView : arbre de l'interface graphique qui affiche l'éxécution des taches
# story : Chaine de caractère à afficher par la tâche en time_task secondes
# block_memory : liste chainée de block
class Task(threading.Thread):
class Priority(Enum):
HIGH = 0
LOW = 1
class State(Enum):
ACTIVE = 0
SLEEPING = 1
def __init__(self, lib_task : str, time_task : int, mem_task : int, level_task : Priority, state_task : State, treeview : ttk.Treeview, story : str, block_memory : MemoryBlock):
self.lib_task = lib_task
self.time_task = time_task
self.index_block = block_memory.add(Block(number_of_blocks=int(mem_task / Block._SIZE_), state= Block.State.BUSY, data = story))
self.story = story
self.block_memory = block_memory
self.level_task = level_task
self.state_task = state_task
self.treeview = treeview
self.block_memory = block_memory
threading.Thread.__init__(self)
def run(self):
self.state_task = Task.State.ACTIVE
data_to_display = self.block_memory[self.index_block].data.decode()[0:len(self.story)]
nb_to_display_each_sec = int(len(data_to_display) / self.time_task)
self.treeview.insert("",'end', text=self.lib_task, values = (self.lib_task, ""))
total_display_chars = nb_to_display_each_sec
global is_locked_for_super_user
for i in range(0, self.time_task + 1):
while self.level_task == Task.Priority.LOW and is_locked_for_super_user:
time.sleep(0.5)
for item in self.treeview.get_children():
if self.treeview.item(item)["text"] == self.lib_task:
self.treeview.item(item, values = (self.lib_task, data_to_display[0:total_display_chars]))
total_display_chars += nb_to_display_each_sec
break
time.sleep(1)
self.treeview.item(item, values = (self.lib_task, data_to_display))
self.state_task = Task.State.SLEEPING
self.block_memory[self.index_block].state = Block.State.FREE
### Thread permettant de gérer l'éxécution de toutes les taches ###
# memoryBlock : liste chainée de block
# stories : liste de chaine de caractères que les taches executerons
# treeView : arbre de l'interface graphique qui affiche l'éxécution des taches
class TaskManager(threading.Thread):
def __init__(self, memoryBlock: MemoryBlock, stories, priority : Task.Priority, treeView : ttk.Treeview):
self.memoryBlock = memoryBlock
self.stories = stories
self.priority = priority
self.treeView = treeView
threading.Thread.__init__(self)
def run(self):
global is_locked_for_super_user
while self.priority == Task.Priority.LOW and is_locked_for_super_user:
time.sleep(0.5)
# launch tasks
shuffle(self.stories)
tasks = []
for index, story in enumerate(self.stories):
task = Task(lib_task="task " + str(index), time_task=__TIME_TASK_S__, mem_task=Block._SIZE_ * __NUMBER_BLOCKS_BY_TASK__, level_task=self.priority, state_task=Task.State.SLEEPING, treeview=self.treeView, story=story, block_memory=self.memoryBlock)
task.start()
tasks.append(task)
# une tache dormante, une fois arrivé son tour d’exécution, elle donne la main à la suivante.
while task.state_task == Task.State.SLEEPING:
time.sleep(0.1)
# Wait until tasks are finished
for t in tasks:
t.join()
### Récupère la mémoire utilisée ###
# Retourne la mémoire utilisée en Mo
def get_memory_usage():
return psutil.Process(os.getpid()).memory_info().rss / __KO_SIZE_BYTE__ / 1024 # Mo
### Lancée par Thread dans le but de superviser le lancement des taches ###
# memoryBlock : liste chainée de block
# stories : liste de chaine de caractères que les taches executerons
# treeView : arbre de l'interface graphique qui affiche l'éxécution des taches
def launch_task_manager(memoryBlock : MemoryBlock, stories, priority : Task.Priority, treeView : ttk.Treeview):
# Clear treeview
for row in treeView.get_children():
treeView.delete(row)
global is_locked_for_super_user
if priority == Task.Priority.HIGH:
is_locked_for_super_user = True
taskManager = TaskManager(memoryBlock, stories, priority, treeView)
taskManager.start()
taskManager.join()
# garbage collector
for i in range(memoryBlock.size() -1, -1, -1):
if memoryBlock[i].state == Block.State.FREE:
memoryBlock.remove(i)
if priority == Task.Priority.HIGH:
is_locked_for_super_user = False
### Extrait toutes les lignes à partir d'un fichier ###
# filename : chemin vers le fichier à lire
# Retourne une liste des lignes lues
def read_stories(filename : str):
story = open(filename, 'r')
return [line.rstrip("\n") for line in story.readlines()]
### Supervise la mémoire utilisée et de met à jour l'interface ###
# memory_bar : Jauge de mémoire de l'interface
# memory_desc : Champs label de l'interface descrivant la mémoire utilisé
def monitor_interface(memory_bar : ttk.Progressbar, memory_desc : tk.Text):
try:
max_bar = 0
memory_bar["maximum"] = int(get_memory_usage())
while True:
memory_usage = memory_usage = int(get_memory_usage())
memory_bar["value"] = memory_usage
if memory_usage >= max_bar:
max_bar = memory_usage
memory_bar["maximum"] = max_bar
memory_desc["text"] = str(memory_usage) + ' Mo utilisés / ' + str(max_bar) + ' Mo maximum utilisés'
time.sleep(1)
except Exception:
return
def main():
# initialize head list empty
memoryBlock = MemoryBlock()
# Read story file
stories = read_stories(__FILENAME__)
turtle.title("Garbage Collector")
turtle.ht()
window = turtle.getscreen()
window.setup(800, 600)
# Create Super user Tasks field
canvas = window.getcanvas()
super_tasks_field = ttk.Treeview(canvas.master, columns=["Label", "Execution"], show="headings", height=20)
super_tasks_field.heading('Label', text='Label')
super_tasks_field.column("Label",minwidth=50,width=75)
super_tasks_field.heading('Execution', text='Execution')
super_tasks_field.column("Execution",minwidth=100,width=250)
canvas.create_window(-200, 0, window=super_tasks_field)
# Create super user button
canvas = window.getcanvas()
button = tk.Button(canvas.master, text="Super utilisateur", command=lambda: threading.Thread(target=launch_task_manager, args= (memoryBlock, stories, Task.Priority.HIGH, super_tasks_field)).start(), height=2, width=30)
canvas.create_window(-200, -250, window=button)
# Create user Tasks field
canvas = window.getcanvas()
tasks_field = ttk.Treeview(canvas.master, columns=["Label", "Execution"], show="headings", height=20)
tasks_field.heading('Label', text='Label')
tasks_field.column("Label",minwidth=50,width=75)
tasks_field.heading('Execution', text='Execution')
tasks_field.column("Execution",minwidth=100,width=250)
canvas.create_window(200, 0, window=tasks_field)
# Create user button
canvas = window.getcanvas()
button = tk.Button(canvas.master, text="Utilisateur ordinaire", command=lambda: threading.Thread(target=launch_task_manager, args= (memoryBlock, stories, Task.Priority.LOW, tasks_field)).start(), height=2, width=30)
canvas.create_window(200, -250, window=button)
# Create progress bar for memory usage
canvas = window.getcanvas()
memory_usage = ttk.Progressbar(canvas.master, orient='horizontal',mode='determinate', length=750, value=get_memory_usage(), maximum=100)
canvas.create_window(0,250, window=memory_usage)
# Create text description for memory usage
canvas = window.getcanvas()
memory_usage_description = tk.Label(canvas.master, text="", background="white")
canvas.create_window(0,275, window=memory_usage_description)
# Lancement d'un thread permettant de supervisier la mémoire utilisée
interface_monitoring_th = threading.Thread(target=monitor_interface, args=(memory_usage, memory_usage_description), daemon= False)
interface_monitoring_th.start()
window.mainloop()
if __name__ == '__main__':
main()

How to register and than search a value in CSV file?

I'm trying to register an user and then read the data I just appended. It looks like the csv file is appending the value, but it's not saving it. But this is awkward, because I used the "with open" function at the "registered" function.
def is_registered(ID): #OK
df = read_any_csv(users_path)
x = df.loc[df["ID"] == ID]
if x.empty:
return False
else:
return True
#faz o cadastro do usuario
def register(ID): #OK
x = str(input("Escreva seu nome: "))
name = x.title()
section = int(input("Digite seu setor(111/112/113): "))
data = [name,ID,section]
with open (users_path,'a') as file:
writer = csv.writer(file)
writer.writerow(data)
def start():
#Se o usuario estiver registrado, da as boas vindas a ele, caso nao, registra ele e depois da as boas vindas
if is_registered(ID) == True: #OK
current_user = users_df.loc[users_df["ID"] == ID]
name = current_user["NAME"]
name2 =(name.to_string(index=False))
section = current_user["SECTION"]
print(f"Ola, {name2}, bem vindo ao programa de treinamento Mercedes Benz Brasil!\n")
videos = videos_to_watch(section)
print("Esses sao os videos que faltam serem assistidos:\n")
print(*videos,sep = '\n')
else: #OK
register(ID)
users_df.to_csv("Users.csv",index = False)
current_user = users_df.loc[users_df["ID"] == ID]
print(current_user)
But the csv can't find the data, the result that I got is that:
Digite o ID: aaaaa
Escreva seu nome: leo
Digite seu setor(111/112/113): 113
Empty DataFrame
Columns: [NAME, ID, SECTION]
Index: []
What I actually want is:
Digite o ID: 5DBEF04B
Escreva seu nome: Raul Lopes Camina
Digite seu setor(111/112/113): 113
Ola, Raul Lopes Camina, bem vindo ao programa de treinamento Mercedes Benz Brasil!
You write new data to file but this can't change original users_df and you would have to read it again (instead of write again)
register(ID)
users_df = pd.read_csv("Users.csv") # <-- read instead of write
current_user = users_df.loc[users_df["ID"] == ID]
print(current_user)
Or you should first add to users_df and later save it with to_csv - and then you don't have to read it again.
def register(ID): # OK
global users_df # need it to add to external variable
name = str(input("Escreva seu nome: "))
name = name.title()
section = int(input("Digite seu setor(111/112/113): "))
data = pd.DataFrame({'NAME': [name], 'ID': [ID], 'SECTION': [section]})
users_df = pd.concat([users_df, data]) # <-- add to original `users_df`
users_df.to_csv("Users.csv", index=False)
and later
register(ID)
# without `to_csv()` and `read_csv()`
current_user = users_df.loc[users_df["ID"] == ID]
print(current_user)

Set SimpleCV Camera resolution with the result of a function

I need to set the resolution of a photo taken with SimpleCV using the result returned by a function, this would be the code:
def resolutionselection():
print"""
Ahora tenemos que escoger el formato y resolución de las fotos:
1 - 10x15.
2 - 15x20.
"""
answer = raw_input("→")
if answer == "1":
print("Has seleccionado hacer las fotos en 10x15.\n")
resolution = ['2304', '1536']
return resolution
elif answer == "2":
print("Has seleccionado hacer las fotos en 15x20.\n")
resolution = ['2048', '1536']
return resolution
else:
print("No estamos colaborando...")
exit(0)
px = resolutionselection()
cam = Camera(prop_set={'width':px[0], 'height':px[1]})
But it gives me error:
TypeError: Expected CvCapture for argument 'capture'
EDIT:
I'm posting the full code, to clarify:
# -- coding: utf-8 --
import time
from SimpleCV import Camera
import RPi.GPIO as GPIO
from sys import exit
sequence = 001 # Starts the sequence number for the photos.
event_name = "Event" # Indicates the name of the event, used in the filename of the photos.
kiosk = "./" # Without choosing, same folder as the program.
cam = Camera(prop_set={'width':2304, 'height':1536}) # Initializes the camera with HR 3:2 format.
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def kioskselection():
print"""
Primero, tenemos que escoger el Kiosco que va a imprimir:
1 - Kodak Wedding.
2 - Kodak Voyage.
"""
answer = raw_input("→\t")
if answer == "1":
print("Has seleccionado Kodak Wedding.\n")
kiosk = "/media/kodakwedding/"
return kiosk
elif answer == "2":
print("Has seleccionado Kodak Voyage. \n")
kiosk = "/media/kodakvoyage/"
return kiosk
else:
print("No estamos colaborando...")
exit(0)
def resolutionselection():
print"""
Ahora tenemos que escoger el formato y resolución de las fotos:
1 - 10x15.
2 - 15x20.
"""
answer = raw_input("→\t")
if answer == "1":
print("Has seleccionado hacer las fotos en 10x15.\n")
resolution = [2304, 1536]
print(resolution)
return resolution
elif answer == "2":
print("Has seleccionado hacer las fotos en 15x20.\n")
resolution = [2048, 1536]
return resolution
print(resolution)
else:
print("No estamos colaborando...")
exit(0)
kiosk = kioskselection()
px = resolutionselection()
cam = Camera(prop_set={'width':px[0], 'height':px[1]})
print("PUSH DA BUTTON!")
while True:
input_state = GPIO.input(17)
if input_state == False:
img = cam.getImage()
img.save("%s%s - %d.jpg" % (kiosk, event_name, sequence))
time.sleep(1)
print("Foto '%s - %d.jpg', guardada." % (event_name, sequence))
sequence += 1

Problem with encoding in Python

I'm fairly new to python, and I'm with some problems with encoding.
Please see the code:
# -*- coding: utf-8 -*-
import config # Ficheiro de configuracao
import twitter
import random
import sqlite3
import time
import bitly_api #https://github.com/bitly/bitly-api-python
import feedparser
class TwitterC:
def logToDatabase(self, tweet, timestamp):
# Will log to the database
database = sqlite3.connect('database.db') # Create a database file
cursor = database.cursor() # Create a cursor
cursor.execute("CREATE TABLE IF NOT EXISTS twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT);") # Make a table
# Assign the values for the insert into
msg_ins = tweet
timestamp_ins = timestamp
values = [msg_ins, timestamp_ins]
# Insert data into the table
cursor.execute("INSERT INTO twitter(tweet, timestamp) VALUES(?, ?)", values)
database.commit() # Save our changes
database.close() # Close the connection to the database
def shortUrl(self, url):
bit = bitly_api.Connection(config.bitly_username, config.bitly_key) # Instanciar a API
return bit.shorten(url) # Encurtar o URL
def updateTwitterStatus(self, update):
short = self.shortUrl(update["url"]) # Vou encurtar o URL
update_str = update["msg"] + " " + short['url'] # Mensagem em bruto, sem tratamento de contagem de caracteres
# I will see how much characters have the message, if more than 140, delete some chars
length_message = len(update_str)
if length_message > 140:
length_url = len(short['url'])
count_message = 136 - length_url
shorten_msg = update["msg"][0:count_message] + '... '
update_str = shorten_msg + short['url']
# Will post to twitter and print the posted text
api = twitter.Api(consumer_key=config.consumer_key,
consumer_secret=config.consumer_secret,
access_token_key=config.access_token_key,
access_token_secret=config.access_token_secret)
status = api.PostUpdate(update_str) # Fazer o update
msg = status.text # Vou gravar o texto enviado para a variavel 'msg'
# Vou gravar p a Base de Dados
self.logToDatabase(msg, time.time())
print msg # So p mostrar o texto enviado. Comentar esta linha de futuro.
# Exemplo base
#x = TwitterC()
#x.updateTwitterStatus({"url": "http://xyz.com/?cat=28", "msg": "Some tips about PostgreSQL Administration?"})
# Solucao para um misto de feeds e frases feitas
# Vou escolher uma fonte ao acaso
p = range(2) # tem o 0 e o 1
p = random.choice(p)
if p == 0: # Escolhe TEXT UPDATES
# Vou escolher um text update ao acaso
text_a_enviar = random.choice(config.text_updates)
update_to_send = text_a_enviar
elif p == 1: # Escolhe FEEDS UPDATES
'''# Vou escolher um feed ao acaso
feed_a_enviar = random.choice(config.feeds_updates)
# Vou apanhar o conteudo do feed
d = feedparser.parse(feed_a_enviar["feedurl"])
# Vou definir quantos feeds quero ter no i
i = range(8)
# Vou meter para "updates" 10 entradas do feed
updates = []
for i in range(8):
updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].summary + ", "}])
# Vou escolher ums entrada ao acaso
update_to_send = random.choice(updates)'''
# Vou postar p o Twitter
x = TwitterC()
x.updateTwitterStatus({"url": "http://xyz.com/", "msg": "favoritos à distancia"})
The code have some lines but the problem is in this line:
x.updateTwitterStatus({"url": "http://xyz.com/", "msg": "favoritos à distancia"})
This line have a character with an accent "à" and this causes the problem here:
def updateTwitterStatus(self, update):
short = self.shortUrl(update["url"]) # Vou encurtar o URL
update_str = update["msg"] + " " + short['url'] # Mensagem em bruto, sem tratamento de contagem de caracteres
...
More precisely in this line:
update_str = update["msg"] + " " + short['url'] # Mensagem em bruto, sem tratamento de contagem de caracteres
The output of the error is this:
x.updateTwitterStatus({"url": "http://xyz.com", "msg": "favoritos à distancia"})
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 48: ordinal not in range(128)
Any clues on how to solve this?
Try adding from __future__ import unicode_literals at the top if your file. Alternatively you can prefix every string with a ´u´, ie u"favoritos à distancia"
Make sure your file is actually saved as utf-8 too!

Categories

Resources