I have an error in a program that I am trying to pass to Kivy. I have a function: askquestions(self,indexquestionlist)
which, as seen, requires the indexquestionlist
parameter. This parameter is the return produced by another function: indexquestions(AnswerDatelist, Atlist)
. The two parameters of this function, AnswerDatelist
and Atlist
are produced by this expression: wordlist, IDQuestionlist, Questionlist, Answerlist, AnswerDatelist, Atlist = Entitylist_matrix()
, but this last function does not think it gives me problems.
To address its resolution I have chosen to create a list called indexquestionlist
within the class VentanaTanda
class VentanaTanda(Screen):
score = NumericProperty()
indexquestionlist = ListProperty([])
(see below in python code)
The problem is that I get the error: NameError: name 'ListProperty' is not defined . For more details: File "C: ... \ main.py", line 255, in WindowTanda indexquestionlist = ListProperty ([]) NameError: name 'ListProperty' is not defined
According to the documentation this property belongs to class kivy.properties.ListProperty
I tried to include this expression where I put all the "import" but I get an error.
The scope of my question is to have a variable, indexquestionlist, that is a list that comes out as a return of the function indexquestions
. After that there will still be failures but I do not intend that you pass the whole program to kivy. With getting what I said before, I'm satisfied.
main.py:
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from random import randint
from datetime import datetime, date, time, timedelta
#DECLARACIÓN DE FUNCIONES
def Date_secondsnow():
now = datetime.now()
Datesecondsnow = now.second + now.minute*60 + now.hour*60*60 + now.day*24*60*60 + now.month*30*24*60*60 + now.year*365*24*60*60
return Datesecondsnow
def addtext(text, a):
a = a + "\n" + text
return a
#CARGAMOS LOS DATOS
#Abrimos el archivo
#Pasamos el archivo de txt a formato de listas de entidad.
def txt_Entitylist():
f = open("Questions CE.txt","r")
filechain = f.read()
#Atención! Asegurate que no hay un caracter EOF después del ultimo "0"
#Saco Entitylist
Entitylist = []
Entitylist = filechain.split("|")
f.close()
return Entitylist
#Función para convertir un txt en una matriz
def Entitylist_matrix():
Entitylist = txt_Entitylist()
#Partimos Entitylist en una lista de palabras (wordlist)
wordlist = []
partx = []
for x in Entitylist:
partx = x.split("^")
a = 0
while a < len(partx):
wordlist = wordlist + [partx[a]]
a = a + 1
#IDQuestionlist
IDQuestionlist = []
i = 0
while i<len(wordlist):
IDQuestionlist = IDQuestionlist + [wordlist[i]]
i = i + 5
#Questionlist
Questionlist = []
i = 1
while i<len(wordlist):
Questionlist = Questionlist + [wordlist[i]]
i = i + 5
#Answerlist
Answerlist = []
i = 2
while i<len(wordlist):
Answerlist = Answerlist + [wordlist[i]]
i = i + 5
#AnswerDatelist
AnswerDatelist = []
i = 3
while i<len(wordlist):
AnswerDatelist = AnswerDatelist + [wordlist[i]]
i = i + 5
#Atlist (Delta time)
Atlist = []
i = 4
while i<len(wordlist):
Atlist = Atlist + [wordlist[i]]
i = i + 5
return wordlist, IDQuestionlist, Questionlist, Answerlist, AnswerDatelist, Atlist
#Función que guarda los datos
def matrix_txt(IDQuestionlist, Questionlist, Answerlist, AnswerDatelist, Atlist):
file=open('Questions CE.txt','w') #Si lo abres en modo "a", añade datos sin borrar los que ya estaban
#1º Quitamos los espacios en blanco que nos sobran de AnswerDatelist y Atlist
#i = 0
#while i<len(Atlist):
# a = str(Atlist[i])
# Atlist[i] = a.strip()
i = 0
while i<len(Atlist):
file.write(""+IDQuestionlist[i]+""+"^")
file.write(""+Questionlist[i]+""+"^")
file.write(""+Answerlist[i]+""+"^")
file.write(" "+str(AnswerDatelist[i]).strip()+" "+"^")
if i + 1 == len(Atlist):
file.write(" "+str(Atlist[i]).strip()+" ")
else:
file.write(" "+str(Atlist[i]).strip()+" "+"^")
i = i + 1
file.close()
#Función para forzar preguntas (se preguntaran las preguntas aunque no haya pasado el tiempo necesario para hacerlas)
def ask_all():
i = 0
answer = 0
while i<len(Atlist) and answer !="exit":
#Mostrar pregunta
print(Questionlist[i])
while answer != "s" and answer != "exit":
print("Una vez que hayas pensado la respuesta debes pulsar s (show answer)")
answer = input()
if answer == "s":
#Inicializo la variable AnswerDatelist ¿y que hay de Atlist?
if int(AnswerDatelist[i]) == 0:
AnswerDatelist[i] = Date_secondsnow()
if int(Atlist[i]) == 0:
Atlist[i] = 1
print(Answerlist[i])
print("A continuación pulsa g (good) si la respuesta que has pensado ha sido buena, o w (wrong) si has fallado")
print("El valor de Atlist es:", Atlist)
while answer !="w" and answer != "g" and answer!="exit":
answer = input()#¿La primera vez que se pasa por el bucle se ejecuta lo que está adentro?
if answer == "w":
Atlist[i] = 1
AnswerDatelist[i] = Date_secondsnow()
if answer == "g":
if 2*int(Atlist[i]) > Date_secondsnow() - int(AnswerDatelist[i]):
Atlist[i] = 2*int(Atlist[i])
else:
Atlist[i] = 2*(Date_secondsnow() - int(AnswerDatelist[i]))
else:
print("Debes pulsar una 'g' o una 'w'")
i = i + 1
#Función para calcular el tiempo que queda para hacer nuevas preguntas
#Qué pasa cuando el resto es negativo?
#Función para preguntar las preguntas que tocan:
def ask():
indexquestionlist = indexquestions(AnswerDatelist, Atlist)
askquestions(indexquestionlist)
#Función que pregunta las preguntas que tocan de dos en dos:
def ask_2():
indexquestionlist = indexquestions(AnswerDatelist, Atlist)
while indexquestionlist != []:
indexquestionlist_2 = []
indexquestionlist = indexquestions(AnswerDatelist, Atlist)
if len(indexquestionlist)>= 2:
indexquestionlist_2 = [indexquestionlist[0]] + [indexquestionlist[1]]
askquestions(indexquestionlist_2)
if len(indexquestionlist) == 1:
indexquestionlist_2 = [indexquestionlist[0]]
askquestions(indexquestionlist_2)
if len(indexquestionlist) == 0:
return -1
indexquestionlist = indexquestions(AnswerDatelist, Atlist)
#Función para guardar datos desde línea de comandos
#def save():
# matrix_txt(IDQuestionlist, Questionlist, Answerlist, AnswerDatelist, Atlist)
def indexquestions(AnswerDatelist, Atlist):
#Primero preguntar las que tienen un AnswerDate = 0
indexquestionlist = []
#Recorremos la lista AnswerDatelist
i = 0
while i<len(AnswerDatelist):
if int(AnswerDatelist[i]) == 0:
indexquestionlist = indexquestionlist + [i]
i = i + 1
#Segundo preguntar las que toca preguntar ¿Cuáles son las que toca preguntar?
#Las que tienen AnswerDate + At < Dateseconds now
i = 0
while i<len(AnswerDatelist):
if int(AnswerDatelist[i]) + int(Atlist[i]) < Date_secondsnow():
indexquestionlist = indexquestionlist + [i]
i = i + 1
indexquestionlist = list(set(indexquestionlist)) #Asi me aseguro de que no hay ninguna pregunta repetida
return indexquestionlist
#indexquestionlist = [] Pensé en definirlo aquí pero nos sigue dando el error de acontinuación. Definimos "indexquestionlist" porque si no, nos da el error File "design.kv", line 99, in <module> on_release: tanda.askquestions(indexquestionlist) NameError: name 'indexquestionlist' is not defined
wordlist, IDQuestionlist, Questionlist, Answerlist, AnswerDatelist, Atlist = Entitylist_matrix()
indexquestionlist = indexquestions(AnswerDatelist, Atlist)
Builder.load_file('design.kv')
class MyScreenManager(ScreenManager):
def __init__(self):
super(MyScreenManager, self).__init__()
class VentanaMenu(Screen):
def save(self):
matrix_txt(IDQuestionlist, Questionlist, Answerlist, AnswerDatelist, Atlist)
class VentanaNuevas(Screen):
def tuq(self): #time until question
#Cómo calcular el tiempo que queda?
tuq_difference = []
tuq_difference_magnitude = []
tuq_difference_scaleoftime = []
chaintuq =""
i = 0
while i<len(Atlist):
tuq_difference = tuq_difference + [int(AnswerDatelist[i])+int(Atlist[i]) - Date_secondsnow()]
i = i + 1
i = 0
while i<len(tuq_difference):
if tuq_difference[i] < 60:
tuq_difference_magnitude = tuq_difference_magnitude + [tuq_difference[i]]
tuq_difference_scaleoftime = tuq_difference_scaleoftime + ["segundos"]
if tuq_difference[i] < 3600 and tuq_difference[i] > 60:
tuq_difference_magnitude = tuq_difference_magnitude + [tuq_difference[i]/60]
tuq_difference_scaleoftime = tuq_difference_scaleoftime + ["minutos"]
if tuq_difference[i] > 3600 and tuq_difference[i] < 3600*24:
tuq_difference_magnitude = tuq_difference_magnitude + [tuq_difference[i]/3600]
tuq_difference_scaleoftime = tuq_difference_scaleoftime + ["horas"]
if tuq_difference[i] > 3600*24 and tuq_difference[i] < 3600*24*30:
tuq_difference_magnitude = tuq_difference_magnitude + [tuq_difference[i]/(3600*24)]
tuq_difference_scaleoftime = tuq_difference_scaleoftime +[ "días"]
if tuq_difference[i] > 3600*24*30 and tuq_difference[i] < 3600*24*30*12:
tuq_difference_magnitude = tuq_difference_magnitude + [tuq_difference[i]/(3600*24*30)]
tuq_difference_scaleoftime = tuq_difference_scaleoftime + ["meses"]
if tuq_difference[i] > 3600*24*30*12:
tuq_difference_magnitude = tuq_difference_magnitude + [tuq_difference[i]/(3600*24*30*12)]
tuq_difference_scaleoftime = tuq_difference_scaleoftime + ["años"]
i = i + 1
i = 0
while i<len(Atlist):
if tuq_difference[i] < 0:
chaintuq = addtext("Ya te toca contestar a la pregunta "+IDQuestionlist[i], chaintuq)
else:
chaintuq = addtext("Para preguntar "+IDQuestionlist[i]+"quedan "+str(tuq_difference_magnitude[i])+" "+tuq_difference_scaleoftime[i], chaintuq)
i = i + 1
self.ids['label4'].text = chaintuq
class VentanaTanda(Screen):
score = NumericProperty()
indexquestionlist = ListProperty([])
#Función que muestra que preguntas hacer
def indexquestions(self,AnswerDatelist, Atlist):
#Primero preguntar las que tienen un AnswerDate = 0
indexquestionlist = []
#Recorremos la lista AnswerDatelist
i = 0
while i<len(AnswerDatelist):
if int(AnswerDatelist[i]) == 0:
indexquestionlist = indexquestionlist + [i]
i = i + 1
#Segundo preguntar las que toca preguntar ¿Cuáles son las que toca preguntar?
#Las que tienen AnswerDate + At < Dateseconds now
i = 0
while i<len(AnswerDatelist):
if int(AnswerDatelist[i]) + int(Atlist[i]) < Date_secondsnow():
indexquestionlist = indexquestionlist + [i]
i = i + 1
indexquestionlist = list(set(indexquestionlist)) #Asi me aseguro de que no hay ninguna pregunta repetida
return indexquestionlist
#Función que hace pregutas
def askquestions(self,indexquestionlist): #Todavía no he terminado esta función
i = 0
answer = 0
while i<len(indexquestionlist) and answer != "exit": #Recorro el vector indexquestionlist
#Mostrar pregunta
a = ""
a = addtext(Questionlist[indexquestionlist[i]],a)
self.ids['label1'].text = a
while answer != "s" and answer != "exit":
a =""
a = addtext("Una vez que hayas pensado la respuesta debes pulsar s (show answer)",a)
answer = input()
if answer == "s":
#Inicializo la variable AnswerDatelist ¿y que hay de Atlist?
if int(AnswerDatelist[indexquestionlist[i]]) == 0:
AnswerDatelist[indexquestionlist[i]] = Date_secondsnow()
if int(Atlist[indexquestionlist[i]]) == 0:
Atlist[indexquestionlist[i]] = 1
print(Answerlist[indexquestionlist[i]])
print("A continuación pulsa g (good) si la respuesta que has pensado ha sido buena, o w (wrong) si has fallado")
print("El valor de Atlist es:", Atlist)
while answer !="w" and answer != "g" and answer!="exit":
answer = input()#¿La primera vez que se pasa por el bucle se ejecuta lo que está adentro?
if answer == "w":
Atlist[indexquestionlist[i]] = 1
AnswerDatelist[indexquestionlist[i]] = Date_secondsnow()
if answer == "g":
if 2*int(Atlist[indexquestionlist[i]]) > Date_secondsnow() - int(AnswerDatelist[indexquestionlist[i]]):
Atlist[indexquestionlist[i]] = 2*int(Atlist[indexquestionlist[i]])
else:
Atlist[indexquestionlist[i]] = 2*(Date_secondsnow() - int(AnswerDatelist[indexquestionlist[i]]))
if answer !="w" and answer !="g":
print("Debes pulsar una 'g' o una 'w'")
i = i + 1
#def showquestion(self):
# with open("question.txt", "r") as f:
# filetext = f.read()
# self.ids['label1'].text = filetext
def showanswer(self):
with open("answer.txt", "r") as f:
filetext = f.read()
self.ids['label2'].text = filetext
class myApp(App):
def build(self):
return MyScreenManager()
def on_pause(self):
return True
def on_resume(self):
pass
if __name__ in ('__main__', '__android__'):
myApp().run()
design.kv:
#:import WipeTransition kivy.uix.screenmanager.WipeTransition
<MyScreenManager>:
transition: WipeTransition()
VentanaMenu:
VentanaNuevas:
VentanaTanda:
<VentanaMenu>:
name: 'menu'
id: menu
AnchorLayout:
BoxLayout:
anchor_x: 'center'
anchor_y: 'center'
padding: 0,10,0,0
spacing: 10
size_hint:1, 0.25
orientation: 'vertical'
# Botones de presentación
Button:
id: button5
text: "Tiempo para nuevas preguntas"
on_release: app.root.current = 'nuevas'; app.root.get_screen('nuevas').tuq()
Button:
id: button6
text: "Hacer tanda de preguntas"
on_release: app.root.current = 'tanda'
Button:
id: button7
text: "Salir"
on_release: menu.save(), app.stop()
<VentanaTanda>:
name: 'tanda'
id: tanda
BoxLayout:
size: root.size
orientation: 'vertical'
padding: 20
spacing: 0
#label1 muestra la pregunta
Label:
id: label1
color: 1,0,1,1
canvas.before:
Color:
rgba: 191/255.0, 144/255.0, 63/255.0, 1
Rectangle:
size: self.size
pos: self.pos
#label2 muestra la respuesta
Label:
id: label2
color: 1,0,1,1
canvas.before:
Color:
rgba: 110/255.0, 191/255.0, 63/255.0, 1
Rectangle:
pos:self.pos
size: self.size
Label:
id: label3
color: 1,0,1,1
text: str(tanda.score)
canvas.before:
Color:
rgba: 74/255.0, 25/255.0, 44/255.0, 1
Rectangle:
pos:self.pos
size: self.size
BoxLayout:
padding: 0,10,0,10
spacing: 10
size_hint:1, 0.30
orientation: 'horizontal'
Button:
id: button1
text: "Mostrar respuesta"
on_release: tanda.showanswer()
Button:
id: button2
text: "Pregunta Acertada"
on_release: tanda.score += 10
Button:
id: button3
text: "Pregunta Fallada"
on_release: tanda.score -= 5
Button:
id: button4
text: "Mostrar pregunta"
on_release: tanda.askquestions(tanda.indexquestionlist)
#Botón Para volver al menu
Button:
size_hint:1, 0.25
text: "Volver al menu"
on_release: app.root.current = 'menu'
<VentanaNuevas>
name: 'nuevas'
id: nuevas
BoxLayout:
size: root.size
orientation: 'vertical'
padding: 20
spacing: 10
#label4 muestra el tiempo hasta las preguntas
Label:
id: label4
color: 1,0,1,1
canvas.before:
Color:
rgba: 33/255.0, 127/255.0, 190/255.0, 1
Rectangle:
pos:self.pos
size: self.size
#Botón Para volver al menu
Button:
size_hint:1, 0.10
text: "Volver al menu"
on_release: app.root.current = 'menu'
I also include the "Questions CE.txt" file because the Entitylist_matrix()
function needs it
Questions CE.txt:
CEP1 ^ ¿Cuando es aprobada la constitución española? ^ El 31 de octubre de 1978 ^ 63620252955 ^ 1 ^ CEP2 ^ ¿Cuando es ratificada la constitución española? ^ El 6 de diciembre de 1978 ^ 63620252997 ^ 1 ^ CEP3 ^ ¿Cuando es sancionada la CE? ^ El 27 de diciembre de 1978 ^ 63620253010 ^ 1 ^ CEP4 ^ ¿Por quién es aprobada la CE? ^ Por las cortes ^ 63619108582 ^ 2182800 ^ CEP5 ^ ¿Por quién es ratificada la CE? ^ Por el pueblo español ^ 63619107733 ^ 2186216 ^ CEP6.1 ^ ¿Por quién es sancionada la CE? ^ Por S.M el Rey ^ 63619108620 ^ 2182724 ^ CEP6.2 ^ ¿Ante quién es sancionada la CE? ^ Ante las Cortes ^ 63619108635 ^ 2182676 ^ CEP7.01 ^ ¿Cuántos títulos tiene la constitución? ^ 11 con el título preliminar ^ 0 ^ 0